Yes, as SomeKittens suggested you need to call setName() first.
class A
{
public $name;
public function getName()
{
return $this->name;
}
}
class B extends A
{
public function setName()
{
$this->name = 'Prasad';
}
}
$obj = new B();
$obj->setName();
echo $obj->getName();
However, it might be better to perform the setting of the name in the constructor of B
, as:
class A
{
public $name;
public function getName()
{
return $this->name;
}
}
class B extends A
{
public function B()
{
$this->name = 'Prasad';
}
}
$obj = new B();
echo $obj->getName();
This printed Prasad
for me using http://writecodeonline.com/php/ to test the code.
Even better, pass the name 'Prasad' when creating the new B
object, as:
class A
{
public $name;
public function getName()
{
return $this->name;
}
}
class B extends A
{
public function B( $value = 'Prasad' )
{
$this->name = $value;
}
}
$obj = new B();
echo $obj->getName(), "<br>";
$obj = new B( 'John' );
echo $obj->getName();