Search code examples
phpoopclassinheritanceextend

PHP Object Oriented Issue On My Code


Hi please have a look on bellow code.

<?php
class A
{
    public $name;

    public function getName()
    {
        return $this->name;
    }
}

class B extends A
{
    public function setName()
    {
        $this->name = 'Prasad';
    }
}

$obj = new B();

echo $obj->getName();

?>

Here It's display nothing when I echo the name. Related to the $name in class A. Is this issue is with getName or setName? How can I set the $name variable in class A from extended class B. And how can I get that from a class B object. Appreciate any hint or explanation on what I have missed.


Solution

  • You didn't set the name (using $obj->setName()) before.