php使用对象属性值作为变量名

php使用对象属性值作为变量名,php,Php,我试图在php中为基本类型创建一个包装器类,但在创建“string”类时遇到了一个问题 如果创建一个新类,如$str=new_string()name没有像我预期的那样工作,事实上我不太清楚到底发生了什么 class _string { private $name; public function __construct($name) { $this->name = 'str_' . $name; global $$this-&

我试图在php中为基本类型创建一个包装器类,但在创建“string”类时遇到了一个问题

如果创建一个新类,如
$str=new_string()$str='foo'赋值,那就太好了
当然,这将覆盖
$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  
class\u字符串{
私人$name;
公共函数构造($name){
$this->name='str.'$name;
全局$$this->name;//此:

……是指:

  • 取变量
    $a
  • 投其所好
  • 使用该字符串调用具有该名称的变量
  • 读取属性
    b
  • 由于
    $a
    (在您的案例中
    $this
    )是一个对象,它感觉像一个bug。您可能需要:

    ${$this->name}
    

    太长了,读不下去了,但是我想你有一些缺少的括号:<代码> $$ > > < > ${{$$-> ->名称} /Cord>你想用一个方法处理一个像一个对象的字符串原语吗?NIKIC在PHP的未来……(不是它解决了你在这里试图做的事情)@ MichaelBerkowski,所以本质上,目的是接近代码> $STR= No.String字符串。()
    $str='foo';
    $str->rev();
    尽可能地回显$str//oof
    ,并且。。。
    ${$this->name}