2013-04-11 51 views
0

的靜態屬性,我實現了一個單例模式類,以及誰可以在其他類這樣使用:PHP語法屬性

class myClass { 

private $attr; 

public function __construct() { 

    $this->attr = Singleton::getInstance; 

    echo $this->attr::$sngtAttr; // Throw an error 

     // witch syntax use whithout pass by a temp var ? 

    } 

} 

回答

0

爲$ sngtAttr的靜態屬性?

如果不是,那麼只是:
echo $this->attr->sngtAttr; instead of echo $this->attr::$sngtAttr; 會做到這一點。

否則,因爲是靜態的:

echo Singleton::$sngtAttr;

+0

嗡嗡......我腦中發生了什麼事? 謝謝,對不起。 – 2013-04-11 19:04:55

0

你的問題是什麼呢? 這是你如何做一個單身:

<?php 

class ASingletonClass 
{ 
    // Class unique instance. You can put it as a static class member if 
    // if you need to use it somewhere else than in yout getInstance 
    // method, and if not, you can just put it as a static variable in 
    // the getInstance method. 
    protected static $instance; 

    // Constructor has to be protected so child classes don't get a new 
    // default constructor which would automatically be public. 
    protected final function __construct() 
    { 
     // ... 
    } 

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

     return self::$instance; 
    } 

    // OR : 

    public static function getInstance() 
    { 
     static $instance; 

     if(! isset($instance)) { 
      $instance = new self; 
     } 

     return $instance; 

     // In that case you can delete the static member $instance. 
    } 

    public function __clone() 
    { 
     trigger_error('Cloning a singleton is not allowed.', E_USER_ERROR); 
    } 
} 

?> 

而且不要忘了()當你調用的getInstance,這是一個方法,而不是一個成員。

+0

我現在我現在...扭曲解決它,我怎麼做不想回聲Singleton :: $ sngtAttr; – 2013-04-11 19:07:14