如果您对这个问题有更好的标题,请告诉我:)
到目前为止,我已经通过这样做创建了我的工厂类:
include_once('menu.class.php');
include_once('gallery.class.php');
class Factory {
function new_menu_obj() { return new Menu(Conn::get_conn()); }
function new_gallery_obj($type ='', $id='') { return new Gallery(Conn::get_conn(), $type, $id); }
/* Many more defined functions here */
}
class Conn { // DB connection }
// To create a new class object I just do this
$menu = Factory::new_menu_obj();
$gallery= Factory::new_gallery_obj('some-type','3');
现在我正在尝试通过使用以下代码更动态地执行此操作:
include_once('menu.class.php');
include_once('gallery.class.php');
class Factory {
private $db_conn;
private function __construct() {
$this->db_conn = Conn::get_conn();
}
public function create( $class_name ) {
if ( $this->db_conn === null ) {
$this->db_conn = Conn::get_conn();
}
return new $class_name( $this->db_conn );
}
}
class Conn { // DB connection }
// To create a new class object I just do this
$menu = Factory->create("Menu");
$gallery= Factory->create("Gallery"); // How do I pass more parameters here?
这是提高效率的“正确方法”吗?:)
当我不知道需要传递多少个变量时,如何创建一个传递变量的新对象?使用数组?