2

I'm trying to make a wrapper class for the primitive types in php but I encountered a problem while making a 'string' class;

If a create a new class like $str = new _string(); it would be nice if i could still assign the value with $str = 'foo'; but of course that will overwrite $str and the class will be destroyed.

So I had the (possibly crazy) idea of accessing the class with $str and its value with $$str by creating $$str in the global scope when instantiating $str

The problem is global $$this->name doesn't work as I'd expect, infact I'm not quite sure whats going on.

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  

My aim is to avoid using $str->value='foo' and get as close to $str='foo' as possible

Is this even possible? Or does anyone have a better suggestion?

8
  • 3
    TL;DR but I think you have some missing brackets: $$this->name -- ${$this->name} Commented May 8, 2014 at 16:27
  • 2
    You're aiming to treat a string primitive like an object with methods? Commented May 8, 2014 at 16:28
  • Nikic has a good recent post about this in the future of PHP... (not that it solves what you're trying to do here) Commented May 8, 2014 at 16:30
  • @MichaelBerkowski so in essence the aim is to get as close to $str = new _string(), $str ='foo';,$str->rev();, echo $str // oof as possible Commented May 8, 2014 at 16:31
  • And ircmaxell's original contrasting viewpoint... Commented May 8, 2014 at 16:31

1 Answer 1

2

This:

$$a->b

... means:

  1. Take variable $a
  2. Cast to string
  3. Use the string to call the variable with that name
  4. Read property b

Since $a (in your case $this) is an object, it feels like a bug. You possibly want:

${$this->name}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.