PHP-扩展类 [英] PHP - Extending Class

查看:87
本文介绍了PHP-扩展类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在PHP中完成了很多面向对象的代码,但是直到现在,我所有的类都是单一的",我想您可以调用它.我正在更改几个类(具有5个左右相同的方法)以扩展一个类(以摆脱重复的代码).我遇到了一些问题.

I've done lots and lots of code in PHP that is object-oriented, but up until now, all of my classes have been, "singular", I suppose you can call it. I am in the process of changing several classes (that have 5 or so identical methods) to extend one class (to rid myself of duplicate code). I am running into a few issues.

我正在尝试访问父类中的方法,但是您可以看到问题.

I am trying to access a method in a parent class, but you can see the issue.

父类:

 class DatabaseObject { 

     public static function find_all() {
        return self::find_by_sql("SELECT * FROM " . self::$table_name);
    }
}

儿童班:

class Topics extends DatabaseObject {

    protected static $table_name = "master_cat";
    protected static $db_fields = array('cat_id', 'category');
    public $cat_id;
    public $category;

  }

试图从php/html文件访问该表中所有信息的代码:

Code trying to access all info from this table from php/html file:

$topics=Topics::find_all();

foreach($topics as $topic):
    echo $topic->category;
endforeach; 

如您所见,大多数代码尚未合并到新的工作方式中.我需要更改self :: $ table_name,它不再以我做事的新方式工作.我将有大约5个扩展此对象的类,因此,对此进行编码的最佳方法是什么,因此我可以使用一种方法访问不同的表(而不是在5个不同的类中包括此精确的find_all()方法.

As you can see, Most of the code has not been merged to the new way of doing things. I need to change the self::$table_name which no longer works in the new way I am doing things. I will have about 5 Classes extending this object, so what is the best way of coding this so I can access different tables with one method (rather than including this exact find_all() method in 5 different classes.

推荐答案

您可以尝试使用下面的 进行后期静态绑定. ,否则单例解决方案也应该可以工作:

You could try late static binding as mentioned below, or a singleton solution should work as well:

<?php
abstract class DatabaseObject {
  private $table;
  private $fields;

  protected function __construct($table, $fields) {
    $this->table = $table;
    $this->fields = $fields;
  }

  public function find_all() {
    return $this->find_by_sql('SELECT * FROM ' . $this->table);
  }
}

class Topics extends DatabaseObject {
  private static $instance;

  public static function get_instance() {
    if (!isset(self::$instance)) {
      self::$instance = new Topics('master_cat', array('cat_id', 'category'));
    }

    return self::$instance;
  }
}

Topics::get_instance()->find_all();

这篇关于PHP-扩展类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆