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'
儘可能
這甚至可能嗎?還是有人有更好的建議?
TL; DR但我認爲你有一些缺失的括號:$$這個 - > name' - ''$ {$這個 - >名}'' –
您的目標是使用方法來對待像對象一樣的字符串原語? –
Nikic在PHP的未來有一個[關於這個最近好帖子](http://nikic.github.io/2014/03/14/Methods-on-primitive-types-in-PHP.html)... (不是說它解決了你在這裏要做的事情) –