Reputation: 97
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;
}
}
Upvotes: 2
Views: 833
Reputation: 10919
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
.
Upvotes: 5
Reputation: 8179
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
Upvotes: 0
Reputation: 7566
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) {}
Upvotes: 3
Reputation: 4157
It adds the given product to the list of products stored by the object.
Upvotes: 1