Re: extended class question

From: Date: Mon, 13 Sep 2004 22:26:54 +0000
Subject: Re: extended class question
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-196578@lists.php.net to get a copy of this message
Hello again Ed, This is a tricky thing. When you define a variable as being private, it literally becomes unavailable to child classes, and exists only as the var1 variable in objects of class test. To prove this, try: <?php class a {
    private $a;
    function geta()
    {
        return $this->a;
    }
    function seta($a)
    {
        $this->a = $a;
    }
} class b extends a {
    private $a;
    function echoa()
    {
        echo 'this ' . $this->geta() . "\n";
        echo 'parent ' . parent::geta() . "\n";
    }
    function seta($a)
    {
        $this->a = $a;
        parent::seta($a - 1);
    }
    function geta()
    {
        return $this->a;
    }
} $b = new b; $b->seta(2); $b->echoa(); ?> you can replace the "private $a" in class b with "protected $a" or "public $a" with no errors whatsoever, in essence the private variable $a has no name outside of the a class - that's what makes it private. It's a nice feature. Now we no longer need to document private variables. Users of our classes can simply ignore them and even name their own variables exactly the same way with impunity. Greg Ed Lazor wrote:
How come the output to this script is "World Trade Center" instead of "Pizza Delivery"? Thanks, Ed ---------------------------------------------------------------- <?php class test { private $var1; function __construct() { $this->var1 = "World Trade Center"; } function get_var1() { return $this->var1; } function set_var1($data) { $this->var1 = $data; } } class testing extends test { function __construct() { parent::__construct(); $this->var1 = "Pizza Delivery"; } } $test2 = new testing(); print "var1 = " . $test2->get_var1() . "<br>"; ?>


« previous php.general (#196578) next »