PHP:如何包含一个类

时间:2010-01-03 11:18:39

标签: php include require

我有index.php我希望在其中加入class.twitter.php,我该怎么做?

希望当我将下面的代码放在index.php中时它会起作用。

$t = new twitter();
$t->username = 'user';
$t->password = 'password';

$data = $t->publicTimeline();

6 个答案:

答案 0 :(得分:28)

您的代码应该是

require_once('class.twitter.php');

$t = new twitter;
$t->username = 'user';
$t->password = 'password';

$data = $t->publicTimeline();

答案 1 :(得分:14)

您可以使用以下任一项:

include "class.twitter.php";

require "class.twitter.php";

使用require(或require_once如果要确保在执行期间仅加载一次类将导致在文件不存在时引发致命错误,而{{1只会发出警告。有关详细信息,请参阅http://php.net/requirehttp://php.net/include

答案 2 :(得分:9)

在命令行界面中包含一个带有use关键字的类示例:

除非您还包含或要求php文件,否则PHP命名空间在命令行上不起作用。当php文件位于由php守护进程解释的网站空间中时,您不需要require行。您所需要的只是“使用”系列。

  1. 创建新目录/home/el/bin

  2. 创建一个名为namespace_example.php的新文件,并将此代码放在其中:

    <?php
        require '/home/el/bin/mylib.php';
        use foobarwhatever\dingdong\penguinclass;
    
        $mypenguin = new penguinclass();
        echo $mypenguin->msg();
    ?>
    
  3. 创建另一个名为mylib.php的文件,并将此代码放在那里:

    <?php
    namespace foobarwhatever\dingdong;
    class penguinclass 
    {
        public function msg() {
            return "It's a beautiful day chris, come out and play! " . 
                   "NO!  *SLAM!*  taka taka taka taka."; 
        }   
    }
    ?>   
    
  4. 从命令行运行它:

    el@apollo:~/bin$ php namespace_example.php 
    
  5. 打印:

    It's a beautiful day chris, come out and play!
    NO!  *SLAM!*  taka taka taka taka
    
  6. 请在此处的评论中查看相关说明:http://php.net/manual/en/language.namespaces.importing.php

答案 3 :(得分:6)

我建议你也看看__autoload 这将清理require和includes的代码。

答案 4 :(得分:3)

  1. require('/yourpath/yourphp.php');

    http://php.net/manual/en/function.require.php

  2. require_once('/yourpath/yourphp.php');

    http://php.net/manual/en/function.require-once.php

  3. include '/yourpath/yourphp.php';

    http://www.php.net/manual/en/function.include.php

  4. use \Yourapp\Yourname

    http://php.net/manual/fa/language.namespaces.importing.php

  5. 注意:

    避免使用require_once,因为它很慢:Why is require_once so bad to use?

答案 5 :(得分:1)