这是user.php:
include("databse.php");//retrieving successfully first name and lastname from databse file into user.php
class user
{
public $first_name;
public $last_name;
public static function full_name()
{
if(isset($this->first_name) && isset($this->last_name))
{
return $this->first_name . " " . $this->last_name;
}
else
{
return "";
}
}
}
其他php文件,index.php:
include(databse.php);
include(user.php);
$record = user::find_by_id(1);
$object = new user();
$object->id = $record['id'];
$object->username = $record['username'];
$object->password = $record['password'];
$object->first_name = $record['first_name'];
$object->last_name = $record['last_name'];
// echo $object->full_name();
echo $object->id;// successfully print the id
echo $object->username;//success fully print the username
echo->$object->full_name();//**ERROR:Using $this when not in object context**
?>
答案 0 :(得分:7)
您无法在静态函数中使用$this
。请改用self::
答案 1 :(得分:3)
让full_name
非静态:
public function full_name() {}
您无法从静态方法访问实例变量,但这正是您尝试执行的操作。
如果您使用self
代替$this
,则必须声明$first_name
和$last_name
静态。
我甚至不理解为什么首先将此方法声明为static
。它无论如何都是一种实例方法。
答案 2 :(得分:0)
检查index.php的最后一行。 echo->$object->full_name()
无效。请改用echo $object->full_name()
。
另外,将full_name()
声明为非静态。