2009-09-23 32 views
9

嘿我不知道如何,當我嘗試類的函數內部下面的代碼它會產生一些PHP錯誤,我不能趕上這樣做調用類在另一個類中的PHP

public $tasks; 
$this->tasks = new tasks($this); 
$this->tasks->test(); 

我不知道爲什麼類的發起需要$以此爲參數選擇:■

感謝

class admin 
{ 
    function validate() 
    { 
     if(!$_SESSION['level']==7){ 
      barMsg('YOU\'RE NOT ADMIN', 0); 
      return FALSE; 
     }else{ 
      **public $tasks;** // The line causing the problem 
      $this->tasks = new tasks(); // Get rid of $this-> 
      $this->tasks->test(); // Get rid of $this-> 
      $this->showPanel(); 
     } 
    } 
} 
class tasks 
{ 
    function test() 
    { 
     echo 'test'; 
    } 
} 
$admin = new admin(); 
$admin->validate(); 
+0

什麼是'公共$任務;'在那裏? – brianreavis 2009-09-23 21:32:59

+0

我認爲需要創建另一個類的對象,它所包含的變量是公開的,但我不知道。 – Supernovah 2009-09-23 21:35:19

回答

22

你不能聲明類的方法(函數內的公共$任務。 )如果你不需要使用任務對象,該對象的方法外,你可以做:

$tasks = new Tasks($this); 
$tasks->test(); 

你只需要使用「$這個 - >」使用時要通過類可用一個變量的。

你兩個選擇:

class Foo 
{ 
    public $tasks; 

    function doStuff() 
    { 
     $this->tasks = new Tasks(); 
     $this->tasks->test(); 
    } 

    function doSomethingElse() 
    { 
     // you'd have to check that the method above ran and instantiated this 
     // and that $this->tasks is a tasks object 
     $this->tasks->blah(); 
    } 

} 

class Foo 
{ 
    function doStuff() 
    { 
     $tasks = new tasks(); 
     $tasks->test(); 
    } 
} 

與您的代碼:

class Admin 
{ 
    function validate() 
    { 
     // added this so it will execute 
     $_SESSION['level'] = 7; 

     if (! $_SESSION['level'] == 7) { 
      // barMsg('YOU\'RE NOT ADMIN', 0); 
      return FALSE; 
     } else { 
      $tasks = new Tasks(); 
      $tasks->test(); 
      $this->showPanel(); 
     } 
    } 

    function showPanel() 
    { 
     // added this for test 
    } 
} 
class Tasks 
{ 
    function test() 
    { 
     echo 'test'; 
    } 
} 
$admin = new Admin(); 
$admin->validate(); 
+0

它沒有工作。我剛剛更新了我的問題,我的代碼更詳細的副本 – Supernovah 2009-09-23 21:39:54

+0

感謝您的工作,你只是:) – Supernovah 2009-09-23 21:51:32

+0

謝謝蘭斯,在星期一和星期五的最簡單的東西都被遺忘了,謝謝提醒;-) – ChrisH 2011-03-25 12:35:34

4

你的問題是這行代碼:

public $tasks; 
$this->tasks = new tasks(); 
$this->tasks->test(); 
$this->showPanel(); 

public關鍵字用於類的定義,而不用於類的方法。在PHP中,你甚至不需要在類中聲明成員變量,你可以做$this->tasks=new tasks(),它會爲你添加。