4

I'm wondering if it's possible, and in case it is, how shoud I achive that:

$this->id <-- i have such thing. but to make it more usable i'd like to have $this->(and here to change the values)

for ex: I might have $this->id $this->allID $this->proj_id

how can I make so that actually I have $this->($myvariable here, that has a unique name in it)?

4 Answers 4

8

You can simply use this:

 $variable = 'id';
 if ( isset ( $this->{$variable} )  ) 
 {
    echo $this->{$variable};
 }
Sign up to request clarification or add additional context in comments.

4 Comments

I'd use $this->{$variable} just in case $variable evaluates to something containing a hyphen. $this->some-thing isn't a valid expression whereas $this->{'some-thing'} would work just fine.
@GordyD - ok, I have smth like that actually in my OOP PHP... In my class I have protected static $tableID = 'sched_id'; and in the class that is extended I have smth like this: $this->static::$tableID but it doesn't work..
Again, $this->{$variable} is IMHO better. In your solution, second dollar sign can be easly unnoticed.
@Crashspeeder - Thanks for comments guys. I have updated my answer further to your suggested improvements.
1

Here is the solution : http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members

An example of using it is here :

class myClass {
    /**  Location for overloaded data.  */
    private $myProperties = array();

    public function __set($name, $value)
    {
        $this->myProperties[$name] = $value;
    }

    public function __get($name)
    {
        if (array_key_exists($name, $this->myProperties))
        {
            return $this->data[$name];
        }
    }
}

Comments

0

You should check out the variable variables manual on the PHP site. With that, it could look like:

<?php
   echo ${'this->'.$yourvariable};  
?>

1 Comment

I think $this->{$yourvariable} looks far better.
0

I prefer to use call_user_func and pass the parameters as array instead.

public function dynamicGetterExample()
{
    $property = 'name'; // as an example...
    $getter = 'get'.ucfirst($property);

    $value = call_user_func(array($this,$getter));
    if (empty($value)) {
        throw new \Exception('Required value is empty for property '.$property);
    }

    return $value;
}

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.