我正在尝试从子类访问父类属性,我声明了一个父类人员,一个儿童班学院并且成了一个大学的对象Ram.It给出了错误 请帮忙:
class Person
{
public $name="My name is Ram Singh.";
}
class college extends Person
{
function __construct()
{
echo"Hello college constructor";
}
var $message=$this->name ;
}
$Ram = new college;
echo $Ram->message;
echo $Ram->name;
答案 0 :(得分:3)
您需要在方法中放置任何变量赋值。你不能在班级做这件事。
class Person
{
public $name="My name is Ram Singh.";
}
class college extends Person
{
public $message = '';
public function __construct()
{
echo"Hello college constructor";
$message=$this->name ;
}
}
$Ram = new college;
echo $Ram->message;
echo $Ram->name;
?>
答案 1 :(得分:1)
它应该有用。经过测试:)
class Person
{
public $name="My name is Ram Singh.";
}
class college extends Person
{
public $message;
function __construct()
{
echo"Hello college constructor";
$this->message=$this->name ;
}
}
$Ram = new college;
echo $Ram->message;
echo $Ram->name;
答案 2 :(得分:0)
您的$message
变量被声明为var
,您应该将其声明为public
,以便从班级外部进行访问。
更好的方法是让班级成员protected
然后将访问者编码为getName()
,getMessage()