简体   繁体   中英

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.

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();
  }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM