简体   繁体   English

如何使用另一个文件中的 PHP 类?

[英]How to use a PHP class from another file?

Let's say I've got two files class.php and page.php假设我有两个文件class.phppage.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;在我的 page.php 文件中; how do I go about doing that?我该怎么做? If I do include(LIB.'/class.php');如果我include(LIB.'/class.php'); it yells at me and gives me Fatal error: Cannot redeclare class IUarts in /dir/class.php on line 4它对我大喊大叫并给了我Fatal error: Cannot redeclare class IUarts in /dir/class.php on line 4

You can use include / include_once or require / require_once您可以使用include / include_oncerequire / require_once

require_once('class.php');

Alternatively, use autoloading by adding to page.php或者,通过添加到page.php来使用自动加载

<?php 
function my_autoloader($class) {
    include 'classes/' . $class . '.class.php';
}

spl_autoload_register('my_autoloader');

$vars = new IUarts(); 
print($vars->data);    
?>

It also works adding that __autoload function in a lib that you include on every file like utils.php .它还可以在包含在每个文件(如utils.php中的库中添加__autoload函数。

There is also this post that has a nice and different approach.还有这篇文章有一个很好的和不同的方法。

Efficient PHP auto-loading and naming strategies 高效的 PHP 自动加载和命名策略

In this case, it appears that you've already included the file somewhere.在这种情况下,您似乎已经在某处包含了该文件。 But for class files, you should really "include" them using require_once to avoid that sort of thing;但是对于类文件,你真的应该使用require_once “包含”它们来避免这种事情; 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 require will cause a fatal error if the file doesn't exist, instead of just issuing a warning.) (并且您通常应该使用require[_once] ,而不是include[_once] ,不同之处在于,如果文件不存在, require将导致致命错误,而不仅仅是发出警告。)

Use include_once instead.使用include_once代替。
This error means that you have already included this file.这个错误意味着你已经包含了这个文件。

include_once(LIB.'/class.php');

Use include("class.classname.php");使用include("class.classname.php");

And class should use <?php //code ?> not <? //code ?>并且类应该使用<?php //code ?> not <? //code ?> <?php //code ?> not <? //code ?>

use采用

require_once(__DIR__.'/_path/_of/_filename.php');

This will also help in importing files in from different folders.这也将有助于从不同文件夹导入文件。 Try extends method to inherit the classes in that file and reuse the functions尝试extends方法来继承该文件中的类并重用这些函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM