2014-05-08 195 views
2

我想在php中爲基元類型創建一個包裝類,但是在創建'string'類時遇到了問題;php使用對象屬性值作爲變量的變量名

如果創建一個像$str = new _string();一個新的類這將是很好,如果我能仍然$str = 'foo';但當然,這將覆蓋$str和類將被銷燬的賦值。

所以我實例$str

時不得不通過在全球範圍內創造$$str訪問與$str類及其價值與$$str的(可能是瘋狂的)想法的問題是global $$this->name不工作,我想預計,事實上我不太確定發生了什麼事情。

class _string { 

    private $name; 

    public function __construct($name) { 
     $this->name = 'str_' . $name;  
     global $$this->name;   // <---this doesn't work properly 
     $strName = 'str_' . $name;  //assigning a global variable variable 
     global $$strName;     //from a local variable works fine 
    } 

    public function __toString() { 
     return $this->name; 
    } 

    public function rev() { 
     $strName = $this->name; 
     global $$strName; 
     $$strName=strrev($$strName); 
     $$this->name=strrev($$this->name); 
    }       //  ^
           //  | 
}        //  | 
           //  | 
$str = new _string('str'); //  | 
$$str = 'hello';    //  | 
$str->rev(); //Warning: Attempt to assign property of non-object 
echo $$str;  //olleh 

我的目標是避免使用$str->value='foo'並獲得儘可能接近$str='foo'儘可能

這甚至可能嗎?還是有人有更好的建議?

+3

TL; DR但我認爲你有一些缺失的括號:$$這個 - > name' - ''$ {$這個 - >名}'' –

+2

您的目標是使用方法來對待像對象一樣的字符串原語? –

+0

Nikic在PHP的未來有一個[關於這個最近好帖子](http://nikic.github.io/2014/03/14/Methods-on-primitive-types-in-PHP.html)... (不是說它解決了你在這裏要做的事情) –

回答

2

此:

$$a->b 

...含義:

  1. 以可變$a
  2. 演員串
  3. 使用字符串來調用變量與該名
  4. 閱讀物業b

由於$a(在你的情況下,$this)是一個對象,它感覺就像一個錯誤。你可能想:

${$this->name}