PHP php type-hinting

Gerade eben ist mir etwas sehhhrr komisches aufgefallen:

PHP:
class OmgType {
  protected $foo;
  protected $bar;
}
class testclass {
  public function testtype(OmgType $type) {
    var_dump(is_object($type));
    var_dump($type);
  }
}

$testclass = new testclass();
$testclass->testtype("test");
erwarteter Output wäre eine notice oder error das "testtype" einen Parameter von Typ OmgType erwartet.

Output bei mir:
Code:
bool(false)
string(4) "test"

Getestet unter Windows (php 5.3.2) / Suse (5.3.3)

funktioniert typechecking nur mit built-in types wie array ?

// fail
hab auf beiden maschinen das ganze in symfony getestet d.h liegt wohl am error-handler vom symfony-framework.
 
Zuletzt bearbeitet:
Jep :)

Code:
sheeep@weide:~$ php -v
PHP 5.3.3-1ubuntu9.3 with Suhosin-Patch (cli) (built: Jan 12 2011 16:08:14) 
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
    with Xdebug v2.1.0, Copyright (c) 2002-2010, by Derick Rethans
    with Suhosin v0.9.31, Copyright (c) 2007-2010, by SektionEins GmbH
Code:
Catchable fatal error: Argument 1 passed to testclass::testtype() must be an instance of OmgType, string given, called in /var/www/foo.php on line 18 and defined in /var/www/foo.php on line 11

Call Stack:
    0.0005     331688   1. {main}() /var/www/foo.php:0
    0.0006     332396   2. testclass->testtype() /var/www/foo.php:18
Viel witziger find ich diesen da:

PHP:
<?php

ini_set('display_errors', true);
error_reporting(E_ALL);

class Foo
{
    public function one(integer $type)
    {
        // ...
    }
}

$f = new Foo();
$f->one(1)

?>
Code:
Catchable fatal error: Argument 1 passed to Foo::one() must be an instance of integer, integer given, called in /var/www/foo.php on line 15 and defined in /var/www/foo.php on line 8

Call Stack:
    0.0009     329064   1. {main}() /var/www/foo.php:0
    0.0011     329740   2. Foo->one() /var/www/foo.php:15
must be an instance of integer, integer given
Aus diesem Grund verwende ich obiges Vorgehen nur bei selbstdefinierten Typen.

//edit:
Und genau so stehts auch im Manual:

Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported.
 
Zuletzt bearbeitet:
Zurück
Oben