In PHP it's not possible to return self to chain static methods. This limits the usage of static methods, because chaining is pretty useful and you have to use instances to chain methods.
Are there any reasons why the PHP developers decided not to allow returning self
? Or is it not possible to return self
in OOP in general?
I cannot give you a reason why other than the syntax itself isn't supported. It almost could work in PHP 5.3:
class Foo
{
public static function A()
{
return __CLASS__;
}
public static function B() { }
}
$chain = Foo::A();
$chain::B();
If PHP would parse Foo::A()::B()
then it would work.
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 could be used for chain static methods:
echo Calculator::startFrom(10)
->add(5)
->sub(10)
->get(); // return 5
New self vs. new static
You can't return a 'self' because no OOP language I know allows to return a type as a type (don't know how to rephrase that). However everyone allows to returns an instance of a type. A static method is part of a class definition and it is callable as long as the application runs.
When doing OOP, you should use the static keyword very carefuly, as it's very easy to abuse it. If you want to chain methods then use an object. Static methods should be used only when no state is required and the function simply process an input and returns a result.
When chaining you have to maintain state and that's where you don't use static classes/methods at all (ok there are some cases but those are exceptions and it's not the case here).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With