如何在PHP中包含类
我有文件如何在PHP中包含类,php,include,require,Php,Include,Require,我有文件index.php,我想在其中包含文件class.twitter.php。我该怎么做 希望,当我将下面的代码放入index.php时,它会工作 $t = new twitter(); $t->username = 'user'; $t->password = 'password'; $data = $t->publicTimeline(); 检查: 和 require('/yourpath/yourphp.php') require_一次('/yourpath/
index.php
,我想在其中包含文件class.twitter.php
。我该怎么做
希望,当我将下面的代码放入index.php时,它会工作
$t = new twitter();
$t->username = 'user';
$t->password = 'password';
$data = $t->publicTimeline();
检查:
和
require('/yourpath/yourphp.php')代码>
require_一次('/yourpath/yourphp.php')代码>
包括“/yourpath/yourphp.php”代码>
use\Yourapp\Yourname
避免使用require\u一次,因为它很慢:您的代码应该是
require_once('class.twitter.php');
$t = new twitter;
$t->username = 'user';
$t->password = 'password';
$data = $t->publicTimeline();
您可以使用以下任一选项:
include "class.twitter.php";
或
使用
require
(或require\u once
,如果要确保在执行过程中只加载一次类,则会在文件不存在时引发致命错误,而include
只会引发警告。有关更多详细信息,请参见和。我建议您也看看。这将清除requires和includes的代码。从命令行界面包括一个带有
use
关键字的类示例:
除非还包含或需要PHP文件,否则PHP名称空间不会在命令行上工作。当php文件位于由php守护进程解释的Web空间中时,您不需要require行。你所需要的只是“使用”线路
/home/el/bin
namespace\u example.php
的新文件,并将此代码放入其中:
<?php
require '/home/el/bin/mylib.php';
use foobarwhatever\dingdong\penguinclass;
$mypenguin = new penguinclass();
echo $mypenguin->msg();
?>
<?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.";
}
}
?>
el@apollo:~/bin$ php namespace_example.php
It's a beautiful day chris, come out and play!
NO! *SLAM!* taka taka taka taka
请参阅此处注释中的注释:我修复了您的代码示例-注意,您可以按原样键入代码,而不是使用HTML实体。我不明白如何将此问题与主题分开?这是一个明确的编码问题,它包含代码,问题很容易理解和回答。一个代码示例会很好。@PeterMortensen您可以在这里看到示例:php做得非常好的一件事是documentation@AntonioCS如果您查看PHP文档中大量的非常有用甚至是至关重要的注释,您可能会想仔细考虑一下PHP提供的文档质量。
It's a beautiful day chris, come out and play!
NO! *SLAM!* taka taka taka taka