我有index.php
我希望在其中加入class.twitter.php
,我该怎么做?
希望当我将下面的代码放在index.php中时它会起作用。
$t = new twitter();
$t->username = 'user';
$t->password = 'password';
$data = $t->publicTimeline();
答案 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/require和http://php.net/include
答案 2 :(得分:9)
use
关键字的类示例:除非您还包含或要求php文件,否则PHP命名空间在命令行上不起作用。当php文件位于由php守护进程解释的网站空间中时,您不需要require行。您所需要的只是“使用”系列。
创建新目录/home/el/bin
创建一个名为namespace_example.php
的新文件,并将此代码放在其中:
<?php
require '/home/el/bin/mylib.php';
use foobarwhatever\dingdong\penguinclass;
$mypenguin = new penguinclass();
echo $mypenguin->msg();
?>
创建另一个名为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.";
}
}
?>
从命令行运行它:
el@apollo:~/bin$ php namespace_example.php
打印:
It's a beautiful day chris, come out and play!
NO! *SLAM!* taka taka taka taka
请在此处的评论中查看相关说明:http://php.net/manual/en/language.namespaces.importing.php
答案 3 :(得分:6)
我建议你也看看__autoload 这将清理require和includes的代码。
答案 4 :(得分:3)
require('/yourpath/yourphp.php');
require_once('/yourpath/yourphp.php');
include '/yourpath/yourphp.php';
use \Yourapp\Yourname
注意:
避免使用require_once,因为它很慢:Why is require_once so bad to use?
答案 5 :(得分:1)