Question

I just wanted to implement generic methods on all my classes ( wich represents data from a database ).

I wasn't able to find a reason why this isn't working, any ideas ? (on php 5.3.1)

   class ActiveRecord {
          public function getAttr($attr_name) {
                 foreach( $this as $key => $value) {
                 if( $key == $attr_name )
                        return $value;
                 }

                 throw new Exception( __CLASS__ . " : Attribut introuvable");
          }
    }

   class MyClass extends ActiveRecord { 
        public $toto = "Variable public<br>";
        protected $tutu = "variable protected<br>";
        private $titi = "variable private<br>";
    }

   $class = new MyClass();

   foreach( $class as $key => $value)
          echo $key . " : " . $value . "<br>";

   echo $class->getAttr("toto");
   echo $class->getAttr("tutu");
   echo $class->getAttr("titi");

It Gives me something like this :

toto : Variable public

Variable public
variable protected

Fatal error: Uncaught exception 'Exception' with message 'ActiveRecord : Attribut introuvable' in C:\wamp\www\restau-app\lib\activerecord.php:12 Stack trace: #0 C:\wamp\www\restau-app\index.php(24): ActiveRecord->getAttr('titi') #1 {main} thrown in C:\wamp\www\restau-app\lib\activerecord.php on line 12

I just can't understand why the method extended from the parent class can't iterate on private members of the child class, so it throw me my exception.

Was it helpful?

Solution

A similar question was asked there : Base class not permitted to access private member?

From php.net :

The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top