Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it not possible to return self in PHP?

Tags:

oop

php

static

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?

like image 558
js-coder Avatar asked Feb 28 '12 12:02

js-coder


3 Answers

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.

like image 91
Matthew Avatar answered Oct 02 '22 11:10

Matthew


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

like image 23
Nick Tsai Avatar answered Oct 02 '22 13:10

Nick Tsai


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

like image 32
MikeSW Avatar answered Oct 02 '22 13:10

MikeSW