dongpu5874 2014-09-01 22:19
浏览 19
已采纳

OOP - 如何定义创建的对象? [关闭]

I ask your advise. In my php file there are some classes.

class Template {

public $id;
public $title;
public $text;
public $description;
public $data = array();
public $content_html;
public $width_content = 500;
public $type;
public $time;
public $user;
public $category;
protected $CI;


// The next code works for a one element of array $data
function __construct($data = array()){
    $this->title    = $data['title'];
    $this->text     = $data['text'];
    $this->category = $data['category'];
    $this->type     = $data['type'];
    $this->time     = $data['time'];

    $this->CI =& get_instance();
    $this->user = new InformationUser($data);
}

class Articles extends Template {
}

class News extends Template {
}

class Init {
   public $posts = array('type' => 2);
}

The start point of my classes is a class Init. Inside this class there is array of users posts. In each element array there is a type value, which define what object class I must create. For example:

class Init {
  function define(){
     foreach($this->posts as $val){
      if($val['type'] == 2){
        $article = new Articles($val);
        //TODO $articles
      } else if($val['type'] == 3){
        $news = new News($val);
         //TODO $news
        }
     }
  }
}

I know that is variant is wrong, better to put all array posts() to class. But I can not do this. I need, that for different type of element of array - to work separate class (for news - News class, article - class Article etc.) What do you advise me?

  • 写回答

1条回答 默认 最新

  • douhao7677 2014-09-01 22:47
    关注

    From the minimal info provided.. I assume you are looking for something like this:

        <?php
        class Init {
            public static function define($type, $text)
            {
              switch($type) {
                case 1:
                    return new Articles($text);
                break;
                case 2:
                    return new News($text);
                break;
                default:
                    throw new Exception('Undefined type');
              }
            }
        }
    
    // $template = Init::define(1, 'article text');
    // $template = Init::define(2, 'news text');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路