Variables in OOP

I have a little struggle with this, and I will be very pleased to help.

In a PHP variable, variables can easily be defined as follows:

$a = "myVar";
$$a = "some Text";
print $myVar; //you get "some Text"

Now, how do I do this in an OOP environment? I tried this:

$a = "myVar";
$myObject->$a = "some Text"; //I must be doing something wrong here
print $myObject->myVar; //because this is not working as expected

I also tried $myObject->{$a} = "some Text", but it does not work either. Therefore, I must be wrong somewhere.

Thanks for any help!

+3
source share
2 answers

This works for me:

class foo {
    var $myvar = 'stackover';
}

$a = 'myvar';
$myObject = new foo();
$myObject->$a .= 'flow';
echo $myObject->$a; // prints stackoverflow
+2
source

This should work

class foo {
    var $myvar = 'stackover';
}

$a = 'myvar';
$myObject = new foo();
$myObject->$a = 'some text';
echo $myObject->myvar;
+2
source

Source: https://habr.com/ru/post/1761872/


All Articles