dongxia4880 2014-02-21 17:12
浏览 17

在另一个PHP类中使用许多不同对象实例的最佳方法是什么?

I have a class called Page, which loads a PHP file for the current page, containing all the HTML (template file). In my template file, I want to use instances of other objects, that is initialized outside the Page class (ex. User, PDO or other classes). My problem is, how I do this the smartest way.

In my page class i have a method called get_page() which loads my template file (containing all the code for my GUI.

public function get_page() {
        // Load theme template
        ...

        $template_file = ABSPATH_THEME . 'tpl.' . $result['template_file'] . '.php';

        if(file_exists($template_file)) {
            $page = require_once($template_file);
            return $page;   
        }
    }

As you see the template file are loaded inside my Page class, and therefore will it not access instances of classes initialized outside my Page class.

I can come up with different solutions:

1) I pass all instances of the different classes to my class Page, when constructing my page. I think this is the right way, but can be very complex if I need 5, 10 or 20 different objects in my design.

2) Find a way to include the template file outside the Page class, but triggered from the get_page() function - have no clue how to do this, and if it is a good solution?

Can you please tell me what is best, and if there are some better ways to do it?

  • 写回答

6条回答 默认 最新

  • drvlf9739 2014-02-21 17:16
    关注

    You can just include classes on the top of your php

    eg. /CLASSPATH/ClassName.php

    And then you can create an entity for that class once and use it everywhere

    eg. $entity = new ClassName();

    评论

报告相同问题?

悬赏问题

  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏