echo "devil";

Type hinting in PHP5

14.06.2010 10:48 | PHP

I just tested type hinting in PHP 5.3.2 to see if something any improvements have been made to it since I last checked. Maybe it's worth considering using it?

This is my test script:

class MyFirstClass {
  const constant = 'CONSTANT';

  public function testClass( MySecondClass $MySecondClass ) {
    return $MySecondClass->getValue();
  }

  public function testArray( array $Array ) {
    return "MyFirstClass -> testArray() : ".$Array[0];
  }

  public function testString( string $String ) {
    return "MyFirstClass -> testString() : ".$String;
  }

  public function testInt( int $Int ) {
    return "MyFirstClass -> testInt() : ".$Int;
  }

  public function testConstant( const $Constant ) {
    return "MyFirstClass -> testConstant() : ".$Constant;
  }
}

class MySecondClass {
  public function getValue() {
    return "MySecondClass -> getValue()";
  }
}

$MyFirstClass = new MyFirstClass();

// Testing class
$MySecondClass = new MySecondClass();
echo $MyFirstClass->testClass( $MySecondClass ) . PHP_EOL;
// Result: Success

// Testing array
$Array = array( 'test' );
echo $MyFirstClass->testArray( $Array ) . PHP_EOL;
// Result: Success

// Testing string
$String = "hello world!";
echo $MyFirstClass->testString( $String ) . PHP_EOL;
// Result: Failed!

// Testing integer
$Int = 10;
echo $MyFirstClass->testInt( $Int ) . PHP_EOL;
// Result: Failed!

// Testing constant
echo $MyFirstClass->testConstant( MyFirstClass::constant );
// Result: Failed!


Is it then worth taking into consideration during development? Not really if you ask me. Especially the fact that integer and string are not supported yet is a bit disturbing. If it's not possible to use the thing to it's full extent, why use it all? I'm not convinced by PHP on this matter yet, but hoping they will include full support in PHP 6 at least. Till then I would use type hinting in very special cases or not at all.


Tags: oop, object oriented, php5, type

« Back «

Share |




RSS feed