Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic class variables

Tags:

oop

php

Does PHP have a method of having auto-generated class variables? I think I've seen something like this before but I'm not certain.

public class TestClass {
    private $data = array();

    public function TestClass() {
        $this->data['firstValue'] = "cheese";
    }
}

The $this->data array is always an associative array but they keys change from class to class. Is there any viable way to access $this->data['firstValue'] from $this->firstValue without having to define the link?

And if it is, are there any downsides to it?

Or is there a static method of defining the link in a way which won't explode if the $this->data array doesn't contain that key?

like image 506
Oli Avatar asked Sep 19 '08 12:09

Oli


People also ask

What is a dynamic class?

The term "dynamic" refers to the session dates, specifically, any course that follows non-standard critical enrollment dates and may include courses taught on campus, online or a combination of both. Dynamic courses can start and end at any time before or after the standard semester.

What is dynamic variable in Python?

A dynamic variable name, which can likewise be known as a variable variable, is fundamentally a variable with a name that is the estimation of another variable. Although Python itself is a highly dynamic language, and almost everything in a Python code is an object, it is possible to create dynamic variables in Python.

How do I create a dynamic class in Python?

Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.

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.


1 Answers

See here: http://www.php.net/manual/en/language.oop5.overloading.php

What you want is the "__get" method. There is an example for what you need on the link.

like image 82
Jan Hančič Avatar answered Sep 30 '22 09:09

Jan Hančič