2016-04-25 67 views
-3

使用我想通過函數來​​創建類的新變量:如何在功能定義變量和

CLASS book{ 

    public function set($name){ 
     newvar($name); 
    } 
} 

function newvar($str){ 
    ***???? 
    /// what is code for here*** 
} 

例子:

$x = new BOOK(); 
$x->set('title'); 

$x->title = 'jack'; 
echo 'book title is: ' . $x->title; 

echo '<br>-----------------------------<br>'; 

$x->set('writer'); 
$x->writer = 'tom'; 
echo 'book writer is: ' . $x->writer; 

結果:

+1

你爲什麼要這樣來做任何特別的原因?當你已經有__get/__ set/etc魔術方法時,爲什麼你要使用全局函數? –

回答

1

它的PHP :)

CLASS book{ 
    public function set($name){ 
     $this->$name = null; 
    } 
} 

甚至低於你的代碼可以動態地添加屬性

$x = new book(); 
$x->writer = 'tom'; 

demo