Is it possible to type hint for the child of a class? Say I only want to accept objects that were extended from the Products class, like Books.
class Product {}
class Book extends Product {}
class Cart
{
public function __construct([Product Class Child] $product) // only accepts children of Product class
{}
}
Something like that in the code above? It seems like it is possible, but I want to ensure I am not in error here.
Returning to this post after a long time - it was a long week. Thanks for the responses.
Jeff:
Can you give me an example of a type hint on the product class? I am not used to type hinting yet and don’t know the ins and outs. From what you are suggesting, it looks like maybe if I type hint for class X, class X and all of its descendents will be accepted? Or am I wrong in this interpretation?
(So would this work?)
class Product
{
public function __construct(Product $product_class) {}
}
Arout:
I’m not sure how interfaces would help. I know some of the theory behind them, but putting it into practice is difficult for me. Could you give me a simple example of type hinting in an interface?
Would this work?
Interface MyInterface
{
public method doSomething(Product $product_class).
}
Would this require me to type hint for all doSomething methods in classes that implement this interface, or would it be done automatically so that I only need to make the method: “public method doSomething($product_class)” without the type hinting.