Type Hinting

A partir de PHP 5 introduce Type Hinting. Las funciones ahora son capaces de forzar que los parámetros sean objetos especificando el nombre de la clase en el prototipo de la función.


Ejemplo 19-40. Ejemplo de Type Hinting
<?php// An example classclass MyClass{
    
/**
     * A test function
     *
     * First parameter must be an object of type OtherClass
     */
    
public function test(OtherClass $otherclass) {
        echo 
$otherclass->var;
    }
}
// Another example classclass OtherClass {
    
public $var 'Hello World';
}
?>


Al no satisfacer el tipo al que se le hace referencia resulta en un error fatal.
<?php// An instance of each class$myclass = new MyClass;$otherclass = new OtherClass;
// Fatal Error: Argument 1 must be an object of class OtherClass$myclass->test('hello');
// Fatal Error: Argument 1 must be an instance of OtherClass$foo = new stdClass;$myclass->test($foo);
// Fatal Error: Argument 1 must not be null$myclass->test(null);
// Works: Prints Hello World$myclass->test($otherclass);?>

Type hinting también aplica en funciones:
<?php// An example classclass MyClass {
    
public $var 'Hello World';
}
/**
* A test function
*
* First parameter must be an object of type MyClass
*/
function MyFunction (MyClass $foo) {
    echo 
$foo->var;
}
// Works$myclass = new MyClass;MyFunction($myclass);?>


Type Hints puede solo ser del tipo object. El tradicional type hinting con int y string no está permitidos.

No response to “Type Hinting”