简体   繁体   English

使用私有可见性时,成员的PHP类Heritage和Iteration

[英]PHP class Heritage and Iteration on members when using private visibility

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) (在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 toto:可变公共

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 致命错误:C:\\ wamp \\ www \\ restau-app \\ lib \\ activerecord.php:12中堆栈错误消息:#0 C:\\ wamp \\ www \\ restau-app中未捕获的异常'Exception',消息为'ActiveRecord:Attribut introuvable' \\ index.php(24):ActiveRecord-> getAttr('titi')#1 {main}在第12行的C:\\ wamp \\ www \\ restau-app \\ lib \\ activerecord.php中抛出

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. 我只是不明白为什么从父类扩展的方法不能在子类的私有成员上进行迭代,所以我抛出了异常。

A similar question was asked there : Base class not permitted to access private member? 有人问类似的问题: 基类是否不允许访问私有成员?

From php.net : php.net

The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. 属性或方法的可见性可以通过在声明的前面加上关键字public,protected或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. 声明为protected的成员只能在该类内部以及继承的和父类访问。 Members declared as private may only be accessed by the class that defines the member. 声明为私有的成员只能由定义该成员的类访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM