PiousVenom
PiousVenom

Reputation: 6908

Using value of a variable as a property name

I've got the following class:

class Foo
{
    $bar1 = 'a';
    $bar2 = 'b'

    public function Update($updateInfo)
    {
        $this->$updateInfo['property'] = $updateInfo[$updateInfo['property']];
    }
}

In my code, I've created a Foo object:

$objFoo = new Foo();

Now, I want to be able to update either of the properties, without the update function knowing which. The array would look like this:

$updateInfo['bar1'] = 'newVal';
$updateInfo['property'] = 'bar1';

I remember hearing or reading that something like this is possible in PHP, but I'm currently getting the error:

Object of class could not be converted to string

Am I mistaken in thinking this can be done? Or is there a better way of doing this?

Upvotes: 1

Views: 57

Answers (2)

ishegg
ishegg

Reputation: 9927

You must be using PHP 7+. This is because of a backwards incompatible change in the handling of indirect variables, properties, and methods. In PHP 5, your code works as is because it's being interpreted as

$this->{$updateInfo['property']} = $updateInfo[$updateInfo['property']];

which is your intended behavior. However, in PHP 7+ it's interpreted as

($this->$updateInfo)['property'] = $updateInfo[$updateInfo['property']];

so it gives you the error you're getting.

Make the behavior you want explicit and it will work fine in both versions:

class Foo
{
    private $bar1 = 'a';
    private $bar2 = 'b';

    public function Update($updateInfo)
    {
        $this->{$updateInfo['property']} = $updateInfo[$updateInfo['property']];
    }
}

$objFoo = new Foo();

$updateInfo['bar1'] = 'newVal';
$updateInfo['property'] = 'bar1';
$objFoo->Update($updateInfo);
var_dump($objFoo);

Demo

Upvotes: 4

Barmar
Barmar

Reputation: 780852

Put braces around the value being used as the property:

$this->{$updateInfo['property']} = $updateInfo[$updateInfo['property']];

Upvotes: 3

Related Questions