Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strange php oop behavior, can someone explain?

In a nutshell: a class inherits a function from its parent. This function then gets called on the child, but appears to still have the scope of the parent class. Is this expected behavior?

Consider the following code example:

<?php
class OLTest {
    private $var1 = 10;

    public function getVar1() {
        if (isset($this->var1)) {
            return $this->var1;
        } else {
            return 'undefined';
        }
    }

    public function getVar2() {
        if (isset($this->var2)) {
            return $this->var2;
        } else {
            return 'undefined';
        }
    }
}

class OLTest2 extends OLTest {
    private $var1 = 11;
    private $var2 = 20;
}

$oltest = new OLTest();
$oltest2 = new OLTest2();

echo "calling parent->getVar1\n";
echo $oltest->getVar1() . "\n";

echo "calling parent->getVar2\n";
echo $oltest->getVar2() . "\n";

echo "calling child->getVar1\n";
echo $oltest2->getVar1() . "\n";

echo "calling child->getVar2\n";
echo $oltest2->getVar2() . "\n";
?>

To my understanding, the output should be:

calling parent->getVar1
10
calling parent->getVar2
undefined
calling child->getVar1
11
calling child->getVar2
20

The actual output on my machine is:

calling parent->getVar1
10
calling parent->getVar2
undefined
calling child->getVar1
10
calling child->getVar2
undefined

To add to the confusion, a print_r($this) within either of the functions, will show that the scope is really set to the subclass, yet it's impossible to access the variable.

Can someone clear this up for me?

EDIT: I am using PHP in version 5.3.3-1ubuntu9.5.

like image 202
theintz Avatar asked Jul 26 '26 07:07

theintz


1 Answers

No, the output should definetly be 10, undefined, 10, undefined. The reason is that the variables that are private are visible only to the class defining them (not super or subclasses).

So, when child is called, its methods are defined in the parent object and when they resolve var1 or var2 they check in the scope definied for OLTest. var2 is not accessible too because the declared var2 is only visible inside OLTest2.

To get your output, your should declare these variables protected or public.

like image 111
Kru Avatar answered Jul 28 '26 19:07

Kru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!