Type hinting for a child of a certain class

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.

Your example code is really confusing…
If I’m understanding this even remotely correctly, it sounds like you’d be better off with interfaces

Why don’t you type hint on the Product class itself? Any subclasses (child classes) of Product will be allowed through.

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.