简体   繁体   中英

PHP Class, Interface, Inheritance

I am trying to understand inheritance in php. I have two classes ShopProduct and CdProduct . ShopProduct class have one method getName . CdProduct class inherit (extends) ShopProduct class and have method DoWork . In index.php file I create a one CdProduct object and pass it to the method that takes one parameter like this function Work(ShopProduct $item){...} . Now, I can understand that I can call getName method using $item parameter, and I know that I can call DoWork method using $item , but I can't understand how this is possible... I hope I was clear... :-)

It's possible because the object passed as parameter happens to contain the DoWork method. It's risky calling this sort of methods (belonging to the inheriting class) without type-checking.

Why does it let you give a CdProduct parameter when the mentioned one is ShopProduct ? Well any class derived from the ShopProduct will contain all its attributes and methods, thus not affecting functionality in the method body.

What can be achieved through this is having a Work method that can receive as a parameter any type derived from ShopProduct ( CdProduct , BookProduct , CandyProduct ) without needing a separate function for each type [ WorkCd (CdProduct $item) or WorkBook (BookProduct $item)] that actually does the same thing.

If you really need access to derived-type specific methods and attributes you can do something like a switch on object class name:

switch(get_class($item))
{
     case "CdProduct":
        //CdProduct object specific code here
     break;
     case "BookProduct":
         //BookProduct object specific here
     break;
     //And so and so forth...
 }

The reason why it works is because PHP 5 introduces type hinting: http://php.net/manual/en/language.oop5.typehinting.php . So indeed CdProduct inherits all the public and protected methods and attributed declared in ShopProduct and thus you can call the getName() method. When you pass the CdProduct instance to the Work function which declares the first parameter to be ShopProduct (and not CdProduct ) you are forcing the parameter to be casted to ShopProduct . So if you pass as parameter something different from CdProduct instance, like a string as an example, you have an error, but because of the inheritance this doesn't fail (it should however print a notice).

As you can read from the comments in the link posted above:

ps do note: when used in inherited classes a STRICT-notice comes up, because the function definition of the inherited class doesn't match the parent's definition (different type hinting) - but it works great!

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