1

When generating an object this way AND executing a method, PHP gives an error.

class A {

    static public function b() {

        $o = new get_called_class();                  // works

        $class = get_called_class();
        $o = new $class;                              // works

        $o = (new $class)->method();                  // works

        $o = (new get_called_class())->method();      // doesn't work
        // error message: Class '...\get_called_class' not found

        $o = (new (get_called_class()))->method();    // doesn't work
        // error message: syntax error, unexpected '('
    }
}

Why does the last lines fail?

How to write it in one line?

4
  • The other lines do not work either. You have missing ; and undefined class get_called_class Commented Jul 19, 2019 at 18:53
  • Ok, edited. thanks. But that does not solve the problem :-( Commented Jul 20, 2019 at 9:45
  • @MarkusZeller None of my quedtions were answered. Looking still for an answer to both of my questions. Commented Sep 2, 2019 at 19:33
  • It is simply answered by "If you want to use an instance, store it in a variable." Commented Sep 2, 2019 at 19:36

2 Answers 2

2

Unfortunately you can't do it directly with the function's return value, but you can save it into a variables and use the variable. You can also use static or self constants.

$class = get_called_class();
$o = (new $class())->method();
$o = (new static())->method();
$o = (new self())->method();
Sign up to request clarification or add additional context in comments.

Comments

1

Not possible at all. If you want to use an instance, store it in a variable.

class MyClass {
     public function method(): string {
          return "Hello World";
     }
}

$instance = new MyClass();
$result = $instance->method();

You could work around if you do not need an instance by using a static method.

class MyClass {
     public static function method(): string {
          return "Hello World";
     }
}

$result = MyClass::method();

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.