Arif H-Shigri
Arif H-Shigri

Reputation: 1136

Return Current Object Through Static method

i want to return the current object of a class. As $this variable refers to current object of that class but when i return this i get an error.

here is my code

class Test{
    $name;
    public static function getobj($n){ 
        $this->name; return $this; 
    }
}
$obj= Test::getobj("doc");

Upvotes: 3

Views: 6241

Answers (3)

csandreas1
csandreas1

Reputation: 2388

private static ?Logger $instance = null;


public static function getInstance(): Logger
{
    if (static::$instance === null) {
        static::$instance = new static();
    }

    return static::$instance;
}

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173642

You can't use $this inside a static method, so you'd have to create an instance of the class and then return that:

class Test
{
    public $name;

    public static function getobj($n)
    {
        $o = new self;
        $o->name = $n;

        return $o;
    }
}

$obj = Test::getobj("doc"); // $obj->name == "doc"

Upvotes: 7

simpleigh
simpleigh

Reputation: 2914

I'm afraid you can't do this. Static methods exist without an instance of the class. You can call a static method without having any instances in existence at all. There isn't a $this because there isn't an instance. If you want one then you'll need to create one:

$obj = new Test();

What you probably want to do is something like this:

class Test
{
    private $name;

    public function __construct($name)
    {
        $this->name = $name;
    }
}

Now you can create an instance of the class as follows:

$obj = new Test('doc');

Some comments are referring to something called a Singleton pattern. You can use this if you know you'll only ever want to have one instance of a class in existence. It works by storing that instance in a static variable on the class:

class A()
{
    /**
     * The instance itself
     * @var A
     */
    private static $instance;

    /**
     * Constructor. Private so nobody outside the class can call it.
     */
    private function __construct() { };

    /**
     * Returns the instance of the class.
     * @return A
     */
    public static function getInstance()
    {
        // Create it if it doesn't exist.
        if (!self::$instance) {
            self::$instance = new A();
        }
        return self::$instance;
    }
}

Upvotes: 1

Related Questions