2013-07-13 57 views
-1

我有PHP類的問題上,我會帶來收益率= true或false從一個類的功能,另一個類的另一個功能調用一個成員函數檢查()非對象

<?php 

class CheckCity { 

    private $x = 10; 
    private $y = 10; 

    public function __construct() { 

     $this->x = rand(10, 10); 
     $this->y = rand(10, 10); 

    } 

    public function Check() { 

     $exists = mysql_query("SELECT * FROM _users WHERE x = $this->x AND y = $this->y LIMIT 1"); 

     if (mysql_num_rows ($exists) == 1) { 

      return true; 

     } else { 

      return false; 

     } 

    } 

} 

class setCity extends CheckCity { 

    public function Set() { 
     parent::Check(); 
     if ($setcity->Check() == true) { 

      echo "is TRUE"; 

     } else { 

      echo "is FALSE"; 

     } 

    } 

} 

這是該指數:

<?php 

$conn = mysql_connect('localhost', 'root', '') or die ('Error 1.'); 
mysql_select_db('db', $conn) or die ('Error 2.'); 

include "func.php"; 

$checkcity = new CheckCity(); 
$checkcity->Check(); 

$setcity = new setCity(); 
$setcity->Set(); 

因此,這是錯誤:

Fatal error: Call to a member function Check() on a non-object in /func.php on line 37 

我搜索的錯誤谷歌和我試過很多SOLU但無濟於事。

+0

最好使用大寫字母和成員函數以及其他帶小寫字母的變量名開始類名。 – maxton

+0

我相信當你擴展類的時候,你會將'parent :: Check();'強制轉換爲靜態方法,因此你不能在對象上下文中實例化它。 – samayo

+0

「錯誤...在第37行」哪一行是第37行? – Danack

回答

2

您的代碼:

$setcity->Check() 

應該是:

​​
0

的錯誤是在這裏:

if ($setcity->Check() == true) { 

$ setcity不聲明爲SetCity類的新實例。

class setCity extends CheckCity { 

    public function Set() { 
     if ($this->Check()) { 

      echo "is TRUE"; 

     } else { 

      echo "is FALSE"; 

     } 

    } 

} 

using $this or parent:: to call inherited methods?

這不是嚴格必要做$這一點,但我建議你做的情況下,你覆蓋類(即延長一個)的方法。

0

在你的setCity類中,你引用了一個未聲明的變量$setcity並試圖調用它的一個函數。由於$setcity中沒有課程,所以php會引發致命錯誤。

如果要對該對象的方法中的當前對象進行操作,請使用$this關鍵字。

PS。您應該閱讀一些有關命名您的類和它們的方法的編程最佳實踐... :)

相關問題