Cod*_*ver 7 php oop class include
我正在学习OOP,并且非常混淆彼此使用类.
我共有3节课
//CMS System class
class cont_output extends cont_stacks
{
//all methods to render the output
}
//CMS System class
class process
{
//all process with system and db
}
// My own class to extends the system like plugin
class template_functions
{
//here I am using all template functions
//where some of used db query
}
Run Code Online (Sandbox Code Playgroud)
现在我想使用我自己的类template_functions和两个系统类.但很困惑如何使用它.请帮我理解这个.
编辑:我很抱歉,我忘了在不同的PHP文件中提到我自己的班级.
hek*_*mgl 13
首先,include在使用之前确保你是类文件:
include_once 'path/to/tpl_functions.php';
Run Code Online (Sandbox Code Playgroud)
这应该在index.php中或在使用的类的顶部完成tpl_function.还要注意autoloading课程的可能性:
从PHP5开始,你必须自动加载类.这意味着您注册了一个钩子函数,当您尝试使用尚未包含代码文件的类时,每次都会调用该函数.这样做你不需要include_once在每个类文件中都有语句.这是一个例子:
index.php或任何应用程序入口点:
spl_autoload_register('autoloader');
function autoloader($classname) {
include_once 'path/to/class.files/' . $classname . '.php';
}
Run Code Online (Sandbox Code Playgroud)
从现在开始,您可以访问这些类,而无需担心包含代码文件.试试吧:
$process = new process();
Run Code Online (Sandbox Code Playgroud)
知道了这一点,有几种方法可以使用该template_functions课程
只需使用它:
如果您创建了它的实例,则可以在代码的任何部分访问该类:
class process
{
//all process with system and db
public function doSomethging() {
// create instance and use it
$tplFunctions = new template_functions();
$tplFunctions->doSomethingElse();
}
}
Run Code Online (Sandbox Code Playgroud)
实例成员:
以进程类为例.要使process类中的template_functions可用,您需要创建一个实例成员并在某个地方初始化它,在需要它的地方,构造函数似乎是个好地方:
//CMS System class
class process
{
//all process with system and db
// declare instance var
protected tplFunctions;
public function __construct() {
$this->tplFunctions = new template_functions;
}
// use the member :
public function doSomething() {
$this->tplFunctions->doSomething();
}
public function doSomethingElse() {
$this->tplFunctions->doSomethingElse();
}
}
Run Code Online (Sandbox Code Playgroud)