How to Define a Class Property Value Dynamically in PHP

dynamic class property $$value in php

You only need to use one $ when referencing an object's member variable using a string variable.

echo $this->$string;

Is it possible to define a class property value dynamically in PHP?

You can put it into the constructor like this:

public function __construct() {
$this->fullname = $this->firstname.' '.$this->lastname;
$this->totalBal = $this->balance+$this->newCredit;
}

Why can't you do it the way you wanted? A quote from the manual explains it:

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

For more infromation about OOP properties see the manual: http://php.net/manual/en/language.oop5.properties.php

How to create new property dynamically

There are two methods to doing it.

One, you can directly create property dynamically from outside the class:

class Foo{

}

$foo = new Foo();
$foo->hello = 'Something';

Or if you wish to create property through your createProperty method:

class Foo{
public function createProperty($name, $value){
$this->{$name} = $value;
}
}

$foo = new Foo();
$foo->createProperty('hello', 'something');

PHP set object properties dynamically

http://www.php.net/manual/en/reflectionproperty.setvalue.php

You can using Reflection, I think.

<?php 

function set(array $array) {
$refl = new ReflectionClass($this);

foreach ($array as $propertyToSet => $value) {
$property = $refl->getProperty($propertyToSet);

if ($property instanceof ReflectionProperty) {
$property->setValue($this, $value);
}
}
}

$a = new A();

$a->set(
array(
'a' => 'foo',
'b' => 'bar'
)
);

var_dump($a);

Outputs:

object(A)[1]
public 'a' => string 'foo' (length=3)
public 'b' => string 'bar' (length=3)

Dynamically declaring Variable inside a class in php

Just use the {} syntax:

function __construct($array)
{
foreach ($array as $key => $value)
{
$this->{$key} = $value;
}
}

Setting a static class property dynamically with squiqlies

You can't set dynamically a static property (otherwise wasn't static :P), but you can manage it, example

class Foo {
static $vars;
public static function set( $k, $v ){
self::$vars[$k] = $v;
}
public static function get( $k ){
return isset(self::$vars[$k]) ? self::$vars[$k] : 'error';
}
}

Can you create instance properties dynamically in PHP?

Sort of. There are magic methods that allow you to hook your own code up to implement class behavior at runtime:

class foo {
public function __get($name) {
return('dynamic!');
}
public function __set($name, $value) {
$this->internalData[$name] = $value;
}
}

That's an example for dynamic getter and setter methods, it allows you to execute behavior whenever an object property is accessed. For example

print(new foo()->someProperty);

would print, in this case, "dynamic!" and you could also assign a value to an arbitrarily named property in which case the __set() method is silently invoked. The __call($name, $params) method does the same for object method calls. Very useful in special cases. But most of the time, you'll get by with:

class foo {
public function __construct() {
foreach(getSomeDataArray() as $k => $value)
$this->{$k} = $value;
}
}

...because mostly, all you need is to dump the content of an array into correspondingly named class fields once, or at least at very explicit points in the execution path. So, unless you really need dynamic behavior, use that last example to fill your objects with data.

This is called overloading
http://php.net/manual/en/language.oop5.overloading.php

Retrieve class property value dynamically

PHP doesn't have properties as C# programmers would understand the concept, so you'll have to use methods as the getter and setter, but the principle is exactly the same.

class MyClass {
private $attributes = array ();

public function getSomeAttribute () {
if (!array_key_exists ('SomeAttribute', $this -> attributes)) {
// Do whatever you need to calculate the value of SomeAttribute here
$this -> attributes ['SomeAttribute'] = 42;
}
return $this -> attributes ['SomeAttribute'];
}
// or if you just want a predictable result returned when the value isn't set yet
public function getSomeAttribute () {
return array_key_exists ('SomeAttribute', $this -> attributes)?
$this -> attributes ['SomeAttribute']:
'n/a';
}

public function setSomeAttribute ($value) {
$this -> attributes ['SomeAttribute'] = $value;
}
}

You essentially got the basic ideas right with your implementation, but it does mean a lot of "boilerplate" code. In theory you can avoid a lot of that with __get and __set, but I'd strongly advise against those as they can lead to epic amounts of confusion and nasty logical tangles like the "what happens if the value is set within the class instead of from outside?" issue that you've run into.

How do I dynamically write a PHP object property name?

Update for PHP 7.0

PHP 7 introduced changes to how indirect variables and properties are handled at the parser level (see the corresponding RFC for more details). This brings actual behavior closer to expected, and means that in this case $obj->$field[0] will produce the expected result.

In cases where the (now improved) default behavior is undesired, curly braces can still be used to override it as shown below.

Original answer

Write the access like this:

$obj->{$field}[0]

This "enclose with braces" trick is useful in PHP whenever there is ambiguity due to variable variables.

Consider the initial code $obj->$field[0] -- does this mean "access the property whose name is given in $field[0]", or "access the element with key 0 of the property whose name is given in $field"? The braces allow you to be explicit.

php dynamically created class object has two properties with the same name cant figure out why

Fixed it by just making a new csv file and manually typing the csv headings.
The original file was saved via excel.

My guess is some sort of text encoding was causing the issue.

Editing the the original file by deleting the headings and typing them again wasn't working but creating a new file and typing it out fixed the issue.

Al-tho I have resolved the issue I'd still love to hear anyone's ideas on why this happened and how to make the some generic code to ignore any weird text encoding in the csv file.

I think possible this might have been a better answer if I was in the situation where recreating the source file wasnt an option.
Remove non-utf8 characters from string



Related Topics



Leave a reply



Submit