2010-11-27 5 views
1

이상한 문제. 싱글 톤을 여러 번 사용했지만이 특별한 경우는 작동하지 않습니다. 덤프는 인스턴스가 null이라고 말합니다.PHP OOP 싱글 톤이 객체를 반환하지 않습니다.

define('ROOT', "/"); 
define('INC', 'includes/'); 
define('CLS', 'classes/'); 

require_once(CLS.'Core/Core.class.php'); 

$core = Core::getInstance(); 

var_dump($core->instance); 

$core->settings(INC.'config.php'); 
$core->go(); 

코어 클래스

class Core 
{ 
    static $instance; 

    public $db; 
    public $created = false; 

    private function __construct() 
    { 
     $this->created = true; 
    } 

    static function getInstance() 
    {  
     if(!self::$instance) { 
      self::$instance = new Core(); 
     } else { 
      return self::$instance; 
     } 
    } 

    public function settings($path = null) 
    { 
     ... 
    } 
    public function go() 
    { 
     ... 
    } 

} 

오류 코드

Fatal error: Call to a member function settings() on a non-object in path 

그것은 아마도 바보 오타,하지만 내 편집기에서 오류가 없습니다. 언제나처럼 빠른 응답에 감사드립니다.

당신은 항상 싱글 방식에서 단일 개체를 반환 할 필요가

답변

9

, 여기 당신이 else 문을 가지고 있기 때문에 당신이 없으므로 getInstance의 첫 번째 호출은 아무것도 반환하지 않습니다 :해야

static function getInstance() 
{  
    if(!self::$instance) { 
     self::$instance = new Core(); 
    } else { 
     return self::$instance; 
    } 
} 

귀하의 싱글 방법을 다음과 같이 :

static function getInstance() 
{  
    if(!self::$instance) { 
     self::$instance = new Core(); 
    } 
    return self::$instance; 
} 

또한, 개체가 만들어 졌는지 여부를 나타내는 인스턴스 변수를 가진 것은 거의 쓸모가, 당신은 단지 if(self::$instance !== NULL)을 비교할 수 있습니다 당신은 갈 수 있어요 때문이다. 항상 값을 반환해야

+1

+1 기술적으로'(self :: $! instance! == null)'과'$ this-> '때문에 OP()에서'$ this-> created'비트가 쓸모 없다고 생각합니다. created == true'는 동등합니다. – netcoder

+0

@netcoder 감사합니다. –

+0

나는 지금 알고있다 - 그러나 나는이 오류가 있다는 것을 깨닫지 못했다. 감사합니다 – Misiur

2

의 getInstance -이 같은 변경해야 :로의 getInstance() 메소드를 변경할 필요뿐만 아니라

static function getInstance() 
{  
    if(!self::$instance) { 
     self::$instance = new Core(); 
    } 
    return self::$instance; 
} 
0

:

static function getInstance() {  
    if(!self::$instance) { 
     self::$instance = new Core(); 
    } 
    return self::$instance; 
} 

... 다음 호출에서 인스턴스 자체에서 $ instance를 참조 해제하려고 시도하고 있습니다.

var_dump($core->instance); 

당신도 확인해야합니다

var_dump($core); 

또는

var_dump(Core::$instance); 

...을 $ 코어 = 코어 ::의 getInstance() 호출 후, 동일한 개체 수 있어야한다.

관련 문제