Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Class throws an error, what is wrong

Tags:

php

class

I have the class.

Class User {

    private $_name;
    private $_email;

    public static function factory() {
        return new __CLASS__;
    }

    public function test() {

    }
}

and when i make a static method call using the syntax below.

User::factory();

it throws me following syntax error.

Parse error: syntax error, unexpected T_CLASS_C in htdocs/test/index.php on line 8

the error is being thrown because the Static factory() method is unable to create the object during the static method call.

and when i change the magic constant __CLASSS__ to the name of the current class i.e to User then it works.

what am i missing?

like image 626
Ibrahim Azhar Armar Avatar asked Aug 28 '11 19:08

Ibrahim Azhar Armar


3 Answers

Try:

Class User {

    private $_name;
    private $_email;

    public static function factory() {
            $class = __CLASS__;
            return new $class;
    }

    public function test() {

    }
}
like image 187
Book Of Zeus Avatar answered Oct 04 '22 21:10

Book Of Zeus


Not really sure why your example doesn't works. But what does work is:

public static function factory()
{
    return new self();
}
like image 40
Decent Dabbler Avatar answered Oct 04 '22 19:10

Decent Dabbler


Try this:

$class = __CLASS__;
return new $class;
like image 33
JRL Avatar answered Oct 04 '22 21:10

JRL