【问题标题】:Accessing parent class variables in constructor PHP [duplicate]在构造函数PHP中访问父类变量[重复]
【发布时间】:2018-06-16 21:00:04
【问题描述】:

我有以下课程。

class User extends GenericObject {
    private $table='users';
    private $primary_key='id';
}

class Animal extends GenericObject {
    private $table='animals';
    private $primary_key='id';
}

class GenericObject {
    public static function create_from_db($params) {
        $self = new self();
        //Build PDO query here

        //These echo statemtns fail
        echo $self->table;
        echo $self->primary_key;

        return $self;
    }
}

在我想要做的与这些类接口的代码中:

$animal=Animal::create_from_db($params);
$user=User::create_from_db($other_params);

我使用超类的目的是不必一遍又一遍地复制 create_from_db 函数。

我尝试覆盖父类并调用它,但我不确定完成我想要完成的任务的“正确”方式。

任何提示

【问题讨论】:

  • variable 你的意思是属性?你可以试试parent::。请注意,如果一个类从另一个类扩展,那么您应该拥有子类的所有属性,因为它们在父类上不是私有的。
  • 停止尝试制作活动记录。您不应该混合持久性和域逻辑。

标签: php oop inheritance


【解决方案1】:

“我使用超类的目的是不必一遍又一遍地复制 create_from_db 函数。”这是错误的,为此使用一个特征。 trait 中定义的代码确实可以访问导入它们的类的私有字段。

【讨论】:

    【解决方案2】:

    要访问这些变量,您应该解决两件事。使属性“受保护”而不是私有,以便可以从父类访问它们并将新语句更改为使用“new static()”,因为这将实例化 Animal 或 User 类而不是“new self()”因为它实例化了 GenericObject 类。

    class User extends GenericObject {
        protected $table='users';
        protected $primary_key='id';
    }
    
    class Animal extends GenericObject {
        protected $table='animals';
        protected $primary_key='id';
    }
    
    class GenericObject {
        public static function create_from_db($params=[]) {
            $self = new static();
            //Build PDO query here
    
            //These echo statements will not fail
            echo $self->table . PHP_EOL;
            echo $self->primary_key . PHP_EOL;
    
            return $self;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-09
      • 2020-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多