我刚刚开始学习 php 中的 OOPS。我写了一个简单的程序来实现继承。当不在对象上下文中时,我收到 $this 的致命错误。谁能解释一下这个错误,它是什么意思?
这是我的代码:
<?php
class human{
public $gender;
public function _construct($gender)
{
$this->gender=$gender;
echo $this->get_gender();
}
public function get_gender()
{
return $this->gender;
}
}
class person extends human{
public $name;
public $surname;
public static function set_name($name)
{
$this->name=$name;
}
public static function set_surname($surname)
{
$this->surname=$surname;
}
public static function get_name()
{
return $this->name;
}
public static function get_surname()
{
return $this->surname;
}
}
$john = new person('male');
$john->set_name('John');
$john->set_surname('Williams');
echo $john->get_name().' '.$john->get_surname().'is a '.$john->get_gender();
?>
这里有两个问题:
您已将方法定义为static
。您不应该这样做,因为它们不是,它们依赖于在对象上调用,因为您想要使用对象的非静态属性。
您的构造函数中有一个拼写错误。构造函数的正确名称是__construct
,注意这两个_
一开始。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)