Question

in php, is there any way to directly access any Base Class Property directly Via an object of a derived Class type.

For eg:

class a  
{  
    public $name="Something"; 

    function show()
    {
        echo $this->name;
    }
}; 
class b extends a  
{  
     public $name="Something Else";  

     function show()
     {
         echo $this->name;
     }
};

$obj = new b();
$obj->show();

it'll Print string "Something Else", but what if i wish to access Base class Function show,

it doesn't seem to work like it is done in c++

obj.a::show();  
Was it helpful?

Solution

Since you override $name in the child, the property will have the child's property value. You cannot access the parent value then. It wouldn't make sense any other way because the property is public, which means the property is visible to the child (and outside) and modifications to it will change the very base value. So it's effectively one and the same property and value for that instance.

The only way to have two separate properties of the same name is to declare the base property private and the child property non-private and then call a method that has access to the base property, e.g.

class Foo
{
    private $name = 'foo';

    public function show()
    {
        echo $this->name;
    }
}

class Bar extends Foo
{
    public $name = 'bar';

    public function show()
    {
        parent::show();
        echo $this->name;
    }
}

(new Bar)->show(); // prints foobar

Since your C++ example call is using the scope resolution operator :: you might be looking for class/static properties:

class Foo
{
    static public $name = 'foo';

    public function show()
    {
        echo static::$name; // late static binding
        echo self::$name;   // static binding
    }
}

class Bar extends Foo
{
    static public $name = 'bar';

    public function show()
    {
        parent::show(); // calling parent's show()
        echo parent::$name; // calling parent's $foo
    }
}

(new Bar)->show(); // prints barfoofoo
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top