2015-10-21 54 views
-1

我有這個控制器我可以在同一個類的方法中訪問私有變量嗎?

class PageController extends Controller 
{  
    private $myid;  
    public funciton index(){ 
    }  
    public function viewbyid($id){ 
     $this->myid = $id; 
    return view('someview'); 
    } 

    public function getRecord(){ 
     $id = $this->myid; 
     echo $id; //it would be null here,if I am going to access this method. 
     return view('anotherview'); 
    } 
} 
+0

是的,這就是'private'手段.... [RTFM(http://www.php.net/manual/en/language.oop5.visibility .php) –

+0

但我試過它返回null – jemz

+0

然後你在哪裏設置它?你在哪裏調用'viewbyid()'? –

回答

0

是的,你可以,你使用PHP OOPS訪問私有varible,在端類的任何地方。所以可能會出現問題,您可能正在使用diff對象訪問getRecord()方法。

對於如:

$obj=new PageController(); 
$obj->viewbyid("Test"); 
$obj->getRecord();//Then it will display the result 

如果您重新初始化的對象或創建新的對象,然後該對象將重新分配內存,所以以前保存的值將不存在。

對於如:

$obj=new PageController(); 
$obj->viewbyid("Test"); 
$obj=new PageController();//$obj will allocate memory in diff location so your previous values will be initialized to default. 
$obj->getRecord();//Then it will display result as null 
相關問題