1

I have a property that stores a class name as a string. I then want to use this to call a static method of said class. As far as I know, this is possible since PHP 5.3. I am running 5.6.x on a vagrant box.

I want to do this:

$item = $this->className::getItem($id);

But I get the following error:

Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)...

The following works fine:

$c = $this->className;
$item = $c::getItem($id);

Any idea why? Is this not the same thing?

8

2 Answers 2

2

The problem is that you are access are property from a class in the first useage, but then in the second try you are parsing the value of the class property (into $c), what is a classname as string, and this can used for static calls to static class functions. The first try, trys to access the static method on an string (the class property).

class a {
     static function b(){echo'works';}
}
$a='a';
$a::b();

But the real issue of the error is, that this ->FooBar:: is an syntax error in PHP.

Sign up to request clarification or add additional context in comments.

Comments

0

JOUM is completely right! Based on his answer I wrote a class like a fabric.

Interface GetItem
{
    public static function getItem($id);
}

Abstract Class Item
{
    private $id;

    function __construct($id)
    {
        $this->id = $id;
    }
}

Class ItemA extends Item implements GetItem
{

    public static function getItem($id)
    {
        $item = new ItemA($id);
        return $item;
    }
}

Class ItemB extends Item implements GetItem
{

    public static function getItem($id)
    {
        $item = new ItemB($id);
        return $item;
    }
}    


Class Fabric
{
    function fabricItem($classname,$id)
    {
        $item = $classname::getItem($id);

        return $item;
    }
}


$fabric = new Fabric();

$a = $fabric->fabricItem("ItemA",3);
$b = $fabric->fabricItem("ItemB",4);    


var_dump($fabric);
var_dump($a);
var_dump($b);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.