ppp
ppp

Reputation: 2055

Access parent property in child class object

I'm just starting with OO php so please forgive my ignorance.

Assuming I have a class A

class A{
    function show(){
        return 15;
        }
    }

And a child class B

class B extends A{
    function show(){
        return 25;
        }
    }

When I do

$object = new B;
$object->show();

I get 25, meaning I access the child property. How can I access the parent property;

I tried $object->A::show(), $object::show(), I keep getting errors, and since I'm just starting, I don't really know what to google for.

Upvotes: 0

Views: 711

Answers (2)

SergeS
SergeS

Reputation: 11779

Thing you want do conflicts basics of object design - if you overwrite parent method, it cannot be called from outside of child instance (inside there is parent:: ). Take a look at your design and try to figure out, how to avoid this.

EDIT: Both of your examples of calling this are invalid - only valid is

class B extends A{
  function show(){
    return parent::show();
  }
}

Upvotes: 4

clem
clem

Reputation: 3366

you are overriding the function show in the child class, so to access it in the parent class you will have to instantiate an object of class a

$object = new A();
$object->show();

There's now way to acccess the parent objects function show() from and instance of the child class

Upvotes: 1

Related Questions