0

We can add any variable to class dynamically in php.

What would be the effect on size(Memory) of class in dynamically addition?

class test
{
public $a;
private $b;

function func1(){...}
}


$obj = new test();
$obj->c ="some value"; 

What will be size of $obj?

Gaurav
  • 28,447
  • 8
  • 50
  • 80
  • 5
    What do you mean by size? Memory footprint, `count`/`sizeof` output, file size? Also are you talking about using a public variable or modifying the class definition before you include it or what? – prodigitalson Feb 22 '11 at 19:23
  • Possibly related to [How to find memory used by an object in PHP?](http://stackoverflow.com/questions/1075419/how-to-find-memory-used-by-an-object-in-php-sizeof) – Leigh Feb 22 '11 at 19:39

1 Answers1

0

The size of the object in memory is going to depend on the content of the variable you're adding. Felix actually answered this already so im just going to use his response:


$a = new C();

print memory_get_usage() . PHP_EOL; 
$a->foo = "bar"; 
print memory_get_usage();

prints

43100
43308

Of course your script needs more memory as you are using more data. However, it has no effect on the class itself as you are adding the property to an instance of the class.


If He decides to undelete his answer i would urge you to accept it as opposed to mine :-)

alex
  • 479,566
  • 201
  • 878
  • 984
prodigitalson
  • 60,050
  • 10
  • 100
  • 114