How to instantiate and call a method in your mouth in PHP?

I tried these two ways:

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

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

Bad luck...

+3
source share
4 answers

You cannot call instanciation and a method in one statement ... But the way to β€œcheat” is to create a function that returns an instance of the class you are working with - and then call a method for this function that returns an object:

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

And in such a situation there is a useful trick: class names and function names do not belong to the same namespace, which means you can have a class and function that have the same name : they do not conflict!

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

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

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

MyClass()->myMethod();

(, , - ;-))

+2

PHP . :

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

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

.

+3

, :

NewsForm::getWidgetSchema();
+1
source

The best option, in my opinion, would be to use the method factory:

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 a factory template. Unfortunately, this only works if you have access to the code and want to change it.

0
source

Source: https://habr.com/ru/post/1735101/


All Articles