简体   繁体   中英

Type hinting in php

So I found this example, I'm learning php oop and I wanted to ask what is the meaning and what it does the argument ShopProduct in method addProduct?

abstract class ShopProductWriter {
    protected $products = array();
    public function addProduct( ShopProduct $shopProduct ) {
        $this->products[]=$shopProduct;
    }
}

lets take this line by line:

abstract class ShopProductWriter {

declares an abstract class named ShopProductWriter . abstract classes cannot be instantiated (you can never have an instance of ShopProductWriter .) In order to use this class you must create a class that extends ShopProductWriter . see http://php.net/manual/en/language.oop5.abstract.php

protected $products = array();

creates a class variable named $products that is an array. The visibility of this variable is protected . This means that $products can only be accessed from within class context using the this operator. Additionally, $this->products will be available to all classes extending ShopProductWriter . see http://php.net/manual/en/language.oop5.visibility.php and http://php.net/manual/en/language.oop5.basic.php

public function addProduct( ShopProduct $shopProduct ) {

defines a public visible function named addProduct , this function can be called outside class context on any class instance extending ShopProductWriter . This function takes a single paramater that must be an instance of ShopProduct OR a child class extending ShopProduct ("If class or interface is specified as type hint then all its children or implementations are allowed too." see http://php.net/manual/en/language.oop5.typehinting.php ).

$childInstance = new ChildCLassExtendingShopProductWriter();
$childInstance->addProduct($IAmAShopProductInstance);

lastly,

$this->products[]=$shopProduct;

the function adds whatever instance was passed into the addProduct function to the class array products .

It means that $shopProduct must be an instance of ShopProduct class

But be aware that type hinting is possible only for objects, arrays and interfaces. You cannot do a type hint for a string, for example

You cannot do

function wontWork(string $string) {}

它将给定的产品添加到对象存储的产品列表中。

ShopProductWriter is an abstract class. and $products is a protected variable where array stored addProduct is a function where list of product stored by the object

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