I have trouble dynamically declaring variables inside a class/object in PHP.
I have a class called Column and it receives an associative array of (names => values) of an unknown length.
I need the class variables to have the exact same name as in the array (and their values to match obviously).
Since Variable Variables method is a bit confusing, when you add on top of it the class/object declaration syntax, I feel I lost myself in it a bit.
I tried something like this:
function __construct($array)
{
foreach ($array as $key => $value)
{
$this->$key;
$this->key=$value;
}
}
i would usually not do this
$this->$key;
I thought $this->key
would fit the syntax,but apparently I was wrong. If someone could help correct me it would very helpful.
The var keyword in PHP is used to declare a property or variable of class which is public by default. The var keyword is same as public when declaring variables or property of a class.
The dynamic variable is a user-defined php code that must return a string value. To create a new dynamic variable, follow these steps: Go to Catalog → Advanced Product Feeds → Dynamic Variables.
A dynamic variable is a variable you can declare for a StreamBase module that can thereafter be referenced by name in expressions in operators and adapters in that module. In the declaration, you can link each dynamic variable to an input or output stream in the containing module.
To call a method dynamically means that we can assign method name to any variable and call the method using that variable, either in switch case of if else block or anywhere depending on our requirement.
Just use the {} syntax:
function __construct($array)
{
foreach ($array as $key => $value)
{
$this->{$key} = $value;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With