如何使用另一个文件中的PHP类? [英] How to use a PHP class from another file?

查看:84
本文介绍了如何使用另一个文件中的PHP类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个文件 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

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自动加载和命名策略

这篇关于如何使用另一个文件中的PHP类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆