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.
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.
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.
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!
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];
}
}
}
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