Bazar behavior w/ private member variables

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi all,

Strangely PHP seems to let each class have its own layer of private scope
for member variables.  If a subclass defines a member variable of the same
name as one defined in the parent the values are maintained independently
in instances of the  child class.

First off a simple class with a private member variable $_myPrivate, and a
public accessor method which returns its value:

class A
{
    private $_myPrivate = 5;

    public function getMyPrivate()
    {
        return $this->_myPrivate;
    }
}


Second, a subclass, that gets weird right away, first we define a private
member variable that already has been defined in the parent class, and give
it a different initial value.  To illustrate the behavior we have two
accessor methods, setMyPrivate that uses the $this keyword to get the value
of $_myPrivate, which returns the value of the subclasse's version of the
variable, and getParentsMyPrivate, that calls A::getMyPrivate via the
parent keyword and it returns the value of $_myPrivate as defined in the
base class.

class B extends A
{
    private $_myPrivate = 6;

    public function setMyPrivate()
    {
        $this->_myPrivate = 6;
    }

    public function getMyPrivate()
    {
        return $this->_myPrivate;
    }

    public function getParentsMyPrivate()
    {
        return parent::getMyPrivate();
    }
}


Look at a var_dump of an instance of B:

object(B)#2 (2) {
  ["_myPrivate":"B":private]=>
  int(6)
  ["_myPrivate":"A":private]=>
  int(5)
}

clearly storage is allocated for two different values.  Now I'm sure you
all know that if I were to define a private method in A and try to call it
from B a Fatal error is raised, something on the order of

PHP Fatal error:  Call to private method A::tryToCallMeFromB() from context
'B'

so why the special treatment for member variables, is this supposed to be a
feature?

-nathan

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux