dqxsuig64994 2013-02-01 21:32 采纳率: 0%
浏览 52
已采纳

PHP:在Child类中调用Abstract方法内部调用property_exists()函数

I want to create the setProperties() method inside of the Abstract class which looks like this:

public function setProperties($array = null) {

        if (!empty($array)) {
            foreach($array as $key => $value) {
                if (property_exists($this, $key)) {
                    $this->{$key} = $value;
                }
            }
        }

    }

What I'm not quite sure about is whether I'll be able to use it in the classes that inherit from this Abstract class to set the inherited properties as well as the child class specific.

I'm not sure if I should use any other keyword then $this in the property_exists() function - perhaps there's a way by using late static bindings (static::) keyword?

  • 写回答

2条回答 默认 最新

  • doucu9677 2013-02-01 21:43
    关注

    Your code should basically work. Imagine this simple example what outputs two times true:

    abstract class A {
    
        protected $var1;
    
        public function exists1() {
            var_dump(property_exists($this, 'var2'));
        }
    
    }
    
    class B extends A {
    
        protected $var2;
    
        public function exists2() {
            var_dump(property_exists($this, 'var1'));
        }
    }
    
    
    $o = new B();
    
    $o->exists1();
    $o->exists2();
    

    As you can see, property_exists() works when the child class is accessing a member from the parent class and vise versa when the parent class is trying to access a member of the child.

    That's one of the basic concepts of abstraction. What you are trying to do is absolutely ok. If you get an error anyway, it must be a little overseen detail

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大