9

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?

2
  • Why don't you return self or $this? Do you need an new instance of the object? Commented Aug 28, 2011 at 19:56
  • yes, i need to create new instance of the object everytime i make call. Commented Aug 28, 2011 at 19:59

4 Answers 4

10

Try:

Class User {

    private $_name;
    private $_email;

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

    public function test() {

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

4 Comments

that of course works, that's not the point, i don't want to create the object that way.
You are trying to create a dynamic return?
hehe, i was missing this trick :), by the way it should be return new $class; not return new $class();
you are correct, but both works since it's a class/object. If you want to pas parameters then you will have to use (). In this case, you don't need.
8

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

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

Comments

7

Try this:

$class = __CLASS__;
return new $class;

2 Comments

it doesn't work :(, throws the following error syntax error, unexpected T_CONSTANT_ENCAPSED_STRING
@Ibrahim Azhar Armar: sorry, my bad, I edited my answer, this time it should work.
3

Why don't you return self or $this?

Check out the singleton patterns: http://www.phpbar.de/w/Singleton and http://php.net/manual/language.oop5.patterns.php

Other solution would be

return clone $this;

1 Comment

You realize you posted a German-language site in the first link?

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.