Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parent object type hinting in PHP

Tags:

php

I'm trying to type hint for a specific parent object in PHP:

I've current got a standard base object class:

class stdObject
{

   private $var;

   public function setVar($var)
   {
     $this->var = $var;
     return $this;
   }
}

And I have a class object that extends this:

class valObject extends stdObject
{
}

In a PHP function, I want to be able to type hint so that the function can expect any object that has a parent of stdObject, so sending in valObject would work but not anyOldObject.

Is this possible?

like image 729
bear Avatar asked Apr 20 '13 14:04

bear


People also ask

What is type hinting in PHP?

Type hinting is a concept that provides hints to function for the expected data type of arguments. For example, If we want to add an integer while writing the add function, we had mentioned the data type (integer in this case) of the parameter.

When was type hinting added PHP?

In May of 2010 support for scalar type hinting was added to the PHP trunk.


2 Answers

You can by using the parent type :

function test(stdObject $obj) {
  // ...
}

If you don't want to have a pure stdObject as parameter, but only an object that inherit stdObject, you should put your stdObject class abstract or create an interface.

like image 84
Alain Tiemblo Avatar answered Sep 19 '22 18:09

Alain Tiemblo


Is this possible?

Yes, what you've descrived is exactly what type hinting is for. Here is the documentation.

like image 25
meagar Avatar answered Sep 17 '22 18:09

meagar