Dynamically add a private property to an object

oop, php

Solution

Just plain, bad design.

What's the purpose of adding a private [!] field at runtime? Existent methods can't rely on such added fields, and you'd be messing with the object functionality.

If you want your object to behave like an hashmap [i.e. you can just call `$obj -> newField = $newValue`], consider using magic `__get` and `__set` methods.

Problem

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.

Original source