我对php类有问题,我会将return=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
我在谷歌上搜索了这个错误,并尝试了许多解决方案,但都无济于事。
您的代码:
$setcity->Check()
应该是:
$this->Check()
在您的setCity类中,您正在引用一个未声明的变量$setcity
,并试图调用它上的函数。由于$setcity
中没有类,php会引发致命错误。
如果要在当前对象的方法中对该对象进行操作,请使用$this
关键字。
PS。您真的应该阅读一些关于命名类及其方法的编程最佳实践…:)
错误在这里:
if ( $setcity->Check() == true ) {
$setcity未声明为setcity类的新实例。
class setCity extends CheckCity {
public function Set() {
if ( $this->Check() ) {
echo "is TRUE";
} else {
echo "is FALSE";
}
}
}
请参阅使用$this或parent::调用继承的方法?
这样做并不是绝对必要的,但我建议您这样做,以防您重写类中的方法(正在扩展的方法)。