Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add a private property to an object

Tags:

oop

php

I have a class:

class Foo {
    // Accept an assoc array and appends its indexes to the object as property
    public function extend($values){
        foreach($values as $var=>$value){
            if(!isset($this->$var))
                $this->$var = $value;
        }
    }
}

$Foo = new Foo;
$Foo->extend(array('name' => 'Bee'));

Now the $Foo object has a public name property with value Bee.

How to change extend function to make variables private ?

Edit Using a private array is another way and definitely not my answer.

like image 335
Omid Avatar asked Nov 16 '12 10:11

Omid


People also ask

How to add dynamic properties to object?

Use the Record utility type to dynamically add properties to an object, e.g. const obj: Record<string, any> . The Record utility type constructs an object type, whose keys and values are of specific type. Copied! const obj: Record<string, any> = { name: 'Tom', }; obj.

Can we add dynamically named properties to JavaScript object?

In JavaScript, you can choose dynamic values or variable names and object names and choose to edit the variable name in the future without accessing the array. To do, so you can create a variable and assign it a particular value.

How to add a property to an object in TypeScript?

To add a property to an object in TypeScript, set the property as optional on the interface you assign to the object using a question mark. You can then add the property at a later point in time without getting a type error. Copied!


1 Answers

You could do something like this.

The __get function will check if the given key is set inside the private property.

class Foo {

private $data = array();

// Accept an array and appends its indexes to the object as property
public function extend($values){
    foreach($values as $i=>$v){
        if(!isset($this->$i))
            $this->data[$i] = $v;
    }
}

public function __get($key) {
    if (isset($this->data[$key])) {
        return $this->data[$key];
    }
}

}
like image 176
Robin Drost Avatar answered Sep 18 '22 02:09

Robin Drost