2016-02-28 60 views
0

我正在寻找一种方法,您可以在类中调用一个静态方法,该方法将创建它自己的一个实例。我喜欢它,所以它不可能在本身之外实例化类。我试过这个,但是我得到一个错误,说无法实例化抽象类(我认为会发生)。只从本身内部实例化类

abstract class Test { 

    public function __construct($item){ 

    } 

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

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

} 

它的使用将是这个样子:

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

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

有没有办法做这样的事情?

+0

看来你是试图为这个类实现一个单例,是吗? –

+1

使构造函数为'private',而不是类'abstract'。 – Marvin

+1

阅读[单身班](http://www.phptherightway.com/pages/Design-Patterns.html)设计模式 –

回答

1

你需要做的构造私有,然后返回该实例..事情是这样的:

class Test { 

    private function __construct($item){ 

    } 

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

} 

现在,您将创建新的情况下,仅是这样的:

$new_object = Test::from('something'); 
+0

这看起来像它会做! –