thanks for replying dlite922,
as you point out, it would not make sense to share attributes (class variables) between objects, because they need to be able to be different from each other.
Static attributes are shared between all objects, that's why they are sometimes called class attributes, rather than instance/object attributes.
But as you may have notice, methods do not change between objects. Let's say the have no state, I was wondering whether they were shared on every instantiation.
You point out the memory cost, but there is also the allocation cpu instuctions cost.
I explain what i mean : PHP is an interpreted language so every piece of code in our scripts is parsed on execution. So every time an instance of a class is created, the class definition must be read and stored in memory, and from that blueprint an instance is created in memory.
That seems fair, if every new instance is of a different class type. But it would be a waste of cpu time to read that class again and again if it were already in memory.
Ex class:
- class A
-
{
-
public $varA;
-
public function methodA()
-
{
-
//20 lines of code
-
}
-
}
-
-
class B
-
{
-
public $varB;
-
public funciton methodB()
-
{
-
//20 lines of more code
-
}
-
}
-
let's create some instances of these two classes :
- $a = new A();
-
$b = new B();
-
$a2 = new A();
-
So here it seems fair that the PHP parser put
class A in memory, then create an instance of that class, by allocating memory for attribure
$varA and
methodA, and then associating the pointer of that instance to variable
$a.
Same thing on line 2 for var
$b as
class B is not already in memory...
But now the important part, for
$a2;
class A was already put in memory so let's reuse that (skip parsing
class A to put it in memory as we already did) and create an instance of
class A. Now that's where my first post question was aimed at : when creating that new instance of
class A do we have to allocate memory for
methodA again, or there is a shared memory for methods?
Well I can summarize the question : how does an object look like in memory?