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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With