[英]how to simply access property of parent class from child class by making object of child class
i am trying to access parent class property from child class, i declared a parent class person, a child class college and made an object Ram of college.It gives error help please: 我试图从子类访问父类属性,我声明了一个父类人,一个子类大学,并创建了对象ram of college。请给出错误帮助:
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;
You need to put any variable assignments inside of methods. 您需要将任何变量分配放入方法内部。 you can't do it at the class level.
您不能在全班学习。
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;
?>
It should work. 它应该工作。 it is tested :)
经过测试:)
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;
Your $message
variable is declared as var
, you should declare it as public
to have access from the outside of the class. 您的
$message
变量被声明为var
,您应该将其声明为public
以便从类外部进行访问。
A better approach is to make the members of the class protected
and then code accessors as getName()
, getMessage()
更好的方法是使该类的成员
protected
,然后将访问器编码为getName()
, getMessage()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.