tags:

views:

54

answers:

4

I tried these two ways:

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

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

With no luck...

+3  A: 

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.

Chacha102
+1  A: 

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

NewsForm::getWidgetSchema();
Mitch C
The poster said in the comments that it's not a static method.
notJim
The comment that the method wasn't static came after I posted this.
Mitch C
+2  A: 

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 ;-) )

Pascal MARTIN
WOW,is it a bug or feature of PHP?
Definitly not a bug ; just a "fact" *(some might call that a feature, I suppose ^^ )*, I would say : class names and function names are not stored in the same data structure, in the internals of PHP, I suppose
Pascal MARTIN
A static factory method within the class would be much more appropriate.
Mitch C
A: 

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.

notJim