0

I am looking for a way where you can call a static method in a class, which will create an instance of itself. I would like it so it isn't possible to instantiate the class outside of itself. I have tried this, but I get an error saying Cannot instantiate abstract class (Which I assumed would happen).

abstract class Test {

    public function __construct($item){

    }

    public static function from($item){
        return new Test($item);
    }

    public function testFunc(){
        // Do some stuff
        return $this;
    }

}

It's usage would look something like this:

// Valid
Test::from($myItem)->testFunc();

// Invalid
(new Test($myItem))->testFunc();

Is there any way to do something like this?

Get Off My Lawn
  • 27,770
  • 29
  • 134
  • 260

1 Answers1

1

You need to make the constructor private and then return the instance.. Something like this:

class Test {

    private function __construct($item){

    }

    public static function from($item){
        return new static($item);
    }

}

Now you would create new instances only like this:

$new_object = Test::from('something');
walther
  • 12,877
  • 5
  • 38
  • 61