Why in PHP it is impossible to return itself?

In PHP, it is not possible to return self in order to bind static methods. This limits the use of static methods because chaining is very useful and you should use instances for chaining methods.

Are there any reasons PHP developers decided not to return self ? Or is it impossible to return self to OOP in general?

+4
source share
4 answers

I can’t name the reason the syntax itself is not supported. It could almost work in PHP 5.3:

 class Foo { public static function A() { return __CLASS__; } public static function B() { } } $chain = Foo::A(); $chain::B(); 

If PHP will parse Foo::A()::B() , then this will work.

+3
source

You cannot return "I", because not a single OOP language that I know allows you to return a type as a type (I don’t know how to rephrase it). However, each allows an instance of the type to be returned. The static method is part of the class definition and can be called while the application is running.

When running OOP, you should use the static keyword very carefully, as it is very easy to offend. If you want to bind methods, use an object. Static methods should only be used when no state is required, and the function simply processes the input and returns the result.

When chaining, you should maintain state and that where you do not use static classes / methods at all (normal, there are some cases, but these are exceptions, and this is not so).

+2
source

If someone who had no relationship with you asked you to give up on yourself and return to something that was not there, how would you feel?

+1
source

Try return new static() or return new self() :

 class Calculator { private static $_var = 0; public static function startFrom($var) { self::$_var = $var; return new static(); } public static function add($var) { self::$_var += $var; return new static(); } public static function sub($var) { self::$_var -= $var; return new static(); } public static function get() { return self::$_var; } } 

This can be used for static circuit methods:

 echo Calculator::startFrom(10) ->add(5) ->sub(10) ->get(); // return 5 

New me versus new static

0
source

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


All Articles