如何使用另一个文件中的PHP类? [英] How to use a PHP class from another file?
问题描述
假设我有两个文件 class.php 和 page.php
class.php
<?php
class IUarts {
function __construct() {
$this->data = get_data('mydata');
}
}
?>
这是一个非常荒唐的例子,但让我说我想使用:
That's a very rudamentary example, but let's say I want to use:
$vars = new IUarts();
print($vars->data);`
在我的page.php文件中;我该怎么做呢?如果我执行include(LIB.'/class.php');
,它会大吼大叫并给我Fatal error: Cannot redeclare class IUarts in /dir/class.php on line 4
in my page.php file; how do I go about doing that? If I do include(LIB.'/class.php');
it yells at me and gives me Fatal error: Cannot redeclare class IUarts in /dir/class.php on line 4
推荐答案
您可以使用 include
/ include_once
或 require_once
You can use include
/include_once
or require
/require_once
require_once('class.php');
或者,使用自动加载
通过添加到page.php
Alternatively, use autoloading
by adding to page.php
<?php
function __autoload($class_name) {
require_once $class_name . '.php';
}
$vars = new IUarts();
print($vars->data);
?>
它还可以在包含在每个文件中的__autoload
函数中添加__autoload
函数,例如utils.php
.
It also works adding that __autoload
function in a lib that you include on every file like utils.php
.
这篇文章也有很好的方法.
There is also this post that has a nice and different approach.
这篇关于如何使用另一个文件中的PHP类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!