简体   繁体   中英

PHP class attribute type hint

I just figured out that PHP5 supports type hinting for function arguments. Is it possible to use this type hinting for class attributes like this:

private FooClass $fo;

Or even for creating new object like this inside function:

FooClass $ff = new FooClass();

No, it is not possible to enforce attribute type like that. But if you'll use decent IDE like PHPStorm you can make a type hint in PHPDoc comment like:

class Foo
    {
    /**
     * @var Bar
     */
    private $barObject;
    }

Then it will check and warn you when you attempt to assign or modify its value with wrong type.

As for enforcing variable type - PHP is a loosely typed language, so no, it's not possible. Again, with decent IDE you can help yourself with PHPDoc comment:

/**
 * @var $bar Bar
 */
$bar = somethingThatReturnsBar();

but that's all.

You can ensure a functions argument is an instance of a specific class using the following code...

$fo = new FooClass();

function myFunction (FooClass $fo){
    // Your Code Here
}

If the $fo argument was not an instance of the FooClass an error would be triggered.

No, although if you feel you really need that you can look at Hack ( http://hacklang.org/ ).

You can, however, control the setting of your private variables by using type hinting in arguments:

class MyClass {
    private $foo;

    public function setFoo(FooClass $foo) {
        $this->foo = $foo;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM