Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically declaring Variable inside a class in php

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.

like image 863
DRVPR Avatar asked Sep 16 '15 12:09

DRVPR


People also ask

How do you declare a class variable in PHP?

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.

What are dynamic variables in PHP?

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.

What is dynamic variable declaration?

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.

What is dynamic method in PHP?

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.


1 Answers

Just use the {} syntax:

function __construct($array)
    {
        foreach ($array as $key => $value)
        {
            $this->{$key} = $value;          
        }
    }
like image 72
laurent Avatar answered Sep 21 '22 15:09

laurent