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');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理