Using $this when not in object context--i am using the latest version of php and mysql
This is 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($t开发者_JAVA技巧his->last_name))
{
return $this->first_name . " " . $this->last_name;
}
else
{
return "";
}
}
}
Other php file, 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**
?>
You cant use $this
in a static function. Use self::
instead
Make full_name
non-static:
public function full_name() {}
You cannot access instance variables from a static method but that is exactly what you are trying to do.
If you use self
instead of $this
, you have to declare $first_name
and $last_name
static as well.
I don't even understand why you declare this method as static
in the first place. It is an instance method by all means.
Check the last line of your index.php. echo->$object->full_name()
is not valid. Use echo $object->full_name()
instead.
Also, declare full_name()
as non-static.
精彩评论