1

I am trying to get a dynamic variable value in a PHP class but not sure how to do this. Here's my code:

<?php
class Test
{
    public $type = "added";

    public $date_added;

    public function set_status()
    {
        $this->date_added = "Pass";
    }

    public function get_status()
    {
        echo $this->date_{$type};
    }
}

$test = new Test();
$test->set_status();
$test->get_status();
?>

I am getting following error:

Notice: Undefined property: Test::$date_ in...

Notice: Undefined variable: type in ...

If I write echo $this->date_added; in place of echo $this->date_{$type}; then I get output "Pass".

How to fix it and do it properly?

3 Answers 3

2

Since you're using variable variables, put them in quotes, then concatenate:

echo $this->{'date_' . $this->type};
                    // not $type, use `$this->` since it's part of your properties

Or using via formatted string (double quotes will work as well):

echo $this->{"date_{$this->type}"};
Sign up to request clarification or add additional context in comments.

2 Comments

So it is called variable of a variable or dynamic variable? Single quotes will not work in your second syntax?
@Sachin yes, that's what PHP calls it. if you use single quotes on the second version, you'll get the literal date_{$this->type}. you need to interpolate the value from $this->type to get date_added, and via double quotes it is possible
1
<?php
class Test
{
    public $type = "added";

    public $date_added;

    public function set_status()
    {
        $this->date_added = "Pass";
    }

    public function get_status()
    {
        echo $this->{'date_' . $this->type};
    }
}

$test = new Test();
$test->set_status();
$test->get_status();
?>

Comments

0

You can do it multiple ways, date_{$type} is not valid expression and to acccess the class property you have to use this keyword .

class Test
{
    public $type = "added";

    public $date_added;

    public function set_status()
    {
        $this->date_added = "Pass";
    }

    public function get_status()
    {
        $prop = 'date_'.$this->type;

        echo $this->{'date_'.$this->type}; # one way to do it
        echo $this->$prop;                  # another way to do it
        echo $this->{"date_{$this->type}"}; # another way to do it
    }
}

$test = new Test();
$test->set_status();
$test->get_status();

3 Comments

What is $prop? Please explain.
$prop is just another variable that holds the actual property value as string, this is a good practice when you have to do some calculation/concatenation/operation to make the final property name like here. $prop = 'date_'.$this->type;
OK, I got it. Thanks.

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.