user198729
user198729

Reputation: 63676

How to do instantiation and call a method in a mouthful in PHP?

I tried these two ways:

(new NewsForm())->getWidgetSchema();

{new NewsForm()}->getWidgetSchema();

With no luck...

Upvotes: 3

Views: 88

Answers (4)

davidtbernal
davidtbernal

Reputation: 13684

A better option in my opinion would be to use a factory method:

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

then

factory_demo::factory()->getWidgetSchema()

Of course, you get all the benefits of the factory pattern as well. Unfortunately this only works if you have access to the code, and are willing to change it.

Upvotes: 0

Pascal MARTIN
Pascal MARTIN

Reputation: 401142

You can't an instanciation and a method call in one instruction... But a way to "cheat" is to create a function that returns an instance of the class you're working with -- and, then, call a method on that function which returns an object :

function my_function() {
    return new MyClass();
}
my_function()->myMethod();

And, in this kind of situation, there is a useful trick : names of classes and names of functions don't belong to the same namespace -- which means you can have a class and a function that have the same name : they won't conflict !

So, you can create a function which has the same name as your class, instanciates it, and returns that instance :

class MyClass {
    public function myMethod() {
        echo 'glop';
    }
}

function MyClass() {
    return new MyClass();
}

MyClass()->myMethod();

(Yeah, the name of the function is not that pretty, in this example -- but you see the point ;-) )

Upvotes: 2

Mitch C
Mitch C

Reputation: 553

If it is a static method you can just do this:

NewsForm::getWidgetSchema();

Upvotes: 1

Tyler Carter
Tyler Carter

Reputation: 61577

PHP does not allow you to do this. Try:

function giveback($class)
{
    return $class;
}

giveback(new NewsForm())->getWidgetSchema();

It is a rather weird quirk with the language.

Upvotes: 3

Related Questions