2013-02-18 56 views
1

在以下腳本中,我嘗試使用對象$objset方法設置$var_1$var_2的值。但是,當我調用get方法來檢索爲該對象設置的值時,我得到一個空白。這是爲什麼 ?

<?php 
class Tester { 

    public $var_1; 
    public $var_2; 

    public function set() { 
     $var_1 = 20; 
     $var_2 = "Tu jo aa jaaye..toh is ghar ko sawanrta dekhun"; 
    } 

    public function get() { 
     return "Var_1 is : {$var_1} and Var_2 is : {$var_2}"; 
    } 
} 

$obj = new Tester(); 
$obj_c = clone $obj; 
$obj_nc = $obj; 

$obj->set(); 
echo $obj->get(); 

echo $obj_nc->get(); 

回答

3

在PHP中需要$this。否則,您引用了局部變量。

public function someFunc() 
{ 
    //$this->var and $var are in no way linked: 
    $var = 1; //A local variable named $var with a value of 1 
    $this->var = 2; // A property of $this object with a value of 2 
} 

作爲一個側面說明,您應該制定與display_errorsOnerror_reporting手搖一路上漲。如果是這樣的話,你會看到你注意到你引用了未定義的變量。 (請注意,error_reporting應該在生產服務器上一路啓動[如果您的代碼是用它編碼的],但生產環境中的display_errors決不應該爲On - 應該使用日誌代替。)

相關問題