如何使用另一个文件中的 PHP 类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14350803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use a PHP class from another file?
提问by Xhynk
Let's say I've got two files class.phpand page.php
假设我有两个文件class.php和page.php
class.php
类.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);`
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
在我的 page.php 文件中;我该怎么做?如果我这样做,include(LIB.'/class.php');它会对我大喊大叫并给我Fatal error: Cannot redeclare class IUarts in /dir/class.php on line 4
回答by Martín Canaval
You can use include/include_onceor require/require_once
您可以使用include/include_once或require/require_once
require_once('class.php');
Alternatively, use autoloadingby adding to page.php
或者,
通过添加到使用自动加载page.php
<?php
function __autoload($class_name) {
require_once $class_name . '.php';
}
$vars = new IUarts();
print($vars->data);
?>
It also works adding that __autoloadfunction in a lib that you include on every file like utils.php.
它还可以__autoload在包含在每个文件中的库中添加该函数,例如utils.php.
There is also this post that has a nice and different approach.
还有这篇文章有一个很好的和不同的方法。
回答by Ry-
In this case, it appears that you've already included the file somewhere. But for class files, you should really "include" them using require_onceto avoid that sort of thing; it won't include the file if it already has been. (And you should usually use require[_once], not include[_once], the difference being that requirewill cause a fatal error if the file doesn't exist, instead of just issuing a warning.)
在这种情况下,您似乎已经在某处包含了该文件。但是对于类文件,您应该真正“包含”它们require_once以避免发生这种事情;如果已经包含该文件,它将不会包含该文件。(并且您通常应该使用require[_once],而不是include[_once],不同之处在于require如果文件不存在,则会导致致命错误,而不仅仅是发出警告。)
回答by Ricardo Alvaro Lohmann
Use include_onceinstead.
This error means that you have already included this file.
使用include_once来代替。
这个错误意味着你已经包含了这个文件。
include_once(LIB.'/class.php');
include_once(LIB.'/class.php');
回答by Manobendronath Biswas
Use include("class.classname.php");
用 include("class.classname.php");
And class should use <?php //code ?> not <? //code ?>
和类应该使用 <?php //code ?> not <? //code ?>
回答by Adnan Fayaz
use
用
require_once(__DIR__.'/_path/_of/_filename.php');
This will also help in importing files in from different folders.
Try extendsmethod to inherit the classes in that file and reuse the functions
这也将有助于从不同文件夹导入文件。Tryextends方法继承该文件中的类并重用函数

