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:
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;
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.
A better approach is to make the members of the class protected
and then code accessors as getName()
, getMessage()
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;
?>