我可以使用PHP为我提供一个包含头文件的类方法吗? [英] Can I have a class method include a header file for me in PHP?
问题描述
请查看下面的示例代码,我有一个类文件已加载到配置文件中.然后将配置文件加载到我构建的任何页面中.是否可以像在show_header()方法中那样包含头文件?似乎不起作用,如何才能达到此结果?
Please review the example code below, I have a class file that is loaded into a config file. The config file is then loaded into any page I build. Is it possible to include a header file the way I have in the show_header() method? It doesn't seem to work so how can I achieve this result?
// Core.class.php
class Core
{
public function show_header($page_name){
require_once 'includes/header.inc.php';
}
}
// config.inc.php
require_once 'Core.class.php';
$core = New core;
// testpage.php
require_once 'config.inc.php';
$core->show_header('home');
这是我要包含到页面中的header.inc.php文件的顶部,似乎可以使用它,但它破坏了头文件的工作方式.
Here is the top part of the header.inc.php file I am trying to include into the page, it seems to work including it but it breaks the way the header file works.
//header.inc.php
<?PHP
//start page timer
$session->get('user_id');
$profiler = new Profiler;
$profiler->start();
//see if site is turned on/off
$core->sitestatus($config['site_status']);
这部分给我这样的错误...
This part gives me errors like this...
注意:未定义的变量:会话在C:\ webserver \ htdocs \ friendproject2 \ includes \ header.inc.php在第5行
Notice: Undefined variable: session in C:\webserver\htdocs\friendproject2\includes\header.inc.php on line 5
致命错误:调用成员函数在非对象中的get()C:\ webserver \ htdocs \ friendproject2 \ includes \ header.inc.php在第5行
Fatal error: Call to a member function get() on a non-object in C:\webserver\htdocs\friendproject2\includes\header.inc.php on line 5
推荐答案
发表评论,听起来您需要一个根Web上下文对象,该对象引用了以下其他对象:
re your comment, sounds like you need a root web context object that you reference the other objects from:
$ctx = WebContext::get();
$ctx->session->get('x');
$ctx->input->get('y');
$ctx->identity->valid;
等等...大多数Web框架都是这样做的.
etc... this is how most web frameworks do it.
需要定义$ session,然后在包含的文件中对其进行引用:
$session would need to be defined, then referenced in the included file:
// If a global variable:
global $session;
$session->get('x');
// If a member of Core:
$this->session->get('x');
是的,您可能会想要 require
而不是 require_once
,并且路径需要基于当前工作目录或绝对路径
yes you can do that, probably you'll want require
instead of require_once
, and the paths would need to be based on the current working directory or an absolute path
尝试添加error_reporting(E_ALL)以查看是否有任何通知...
try adding error_reporting(E_ALL) to see if any notices are happening...
这篇关于我可以使用PHP为我提供一个包含头文件的类方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!