Click to See Complete Forum and Search --> : Scope of protected variable


pizzaman
05-05-2005, 12:41 AM
For example, I have the following code:

<?php
class foo //parent class
{
protected $foovariable;

public function FooFun(bar $BarObj)
{
$BarObj->barvariable = 1; //this is fine
}
}

class bar extends foo //child class extends foo
{
protected $barvariable;

public function BarFun(foo $FooObj)
{
$FooObj->foovariable = 1; //but this gives me a access violation error
}
}
?>

I thought with the protected the child class can access the parent class' variables directly. Unless that is only if the parent class is not passed in as a function parameter?

-Pizzaman

shimon
05-10-2005, 08:43 AM
I think you may have confused a couple of issues there. Making a variable protected in a parent class makes it available within child objects, like so:

<?php

class Parent {
protected $foo;
}

class Child extends Parent {

public function doSomething()
{
$this->foo = 48; // will work fine
}
}

?>

But you still can't address $foo directly from outside the child object itself: what you have tried is no different to the following:

<?php

$child = new Child();
$child->foo = 47;

?>

Which will give you exactly the error message you describe.

Keep at it though :) once you get the hang of objects you'll be 100 times stronger as a programmer than otherwise.