bijiDango bijiDango - 1 month ago 5
PHP Question

In PHP, how can we define a field as a certian class's instance like JAVA?

Then I can use the auto-completion in an IDE.

In

Java
we define a class like

class AppleTree{
Apple apple;
}

class Apple {
Color getColor() {}
}


So when I input
apple.
, the IDE can bring out a list that contains
getColor()
method.

In
PHP
we can define a class like

class AppleTree
{
public $apple;
}

class Apple
{
public function getColor() {}
}

Answer

If your goal is auto-completion you can go with DocBlocks.

class AppleTree
{
    /**
     * @var Apple
     */
    public $apple;
}

class Apple
{
    /**
     * @return Color
     */
    public function getColor() {}
}

However if you want to achieve the behavior that restricts setting anything but instances of given class you have to use type hinting.