开发者_JAVA百科
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this questionI have file index.php
, and I want to include file class.twitter.php
inside it. How can I do this?
Hopefully, when I put the below code in index.php it will work.
$t = new twitter();
$t->username = 'user';
$t->password = 'password';
$data = $t->publicTimeline();
Your code should be something like
require_once('class.twitter.php');
$t = new twitter;
$t->username = 'user';
$t->password = 'password';
$data = $t->publicTimeline();
You can use either of the following:
include "class.twitter.php";
or
require "class.twitter.php";
Using require
(or require_once
if you want to ensure the class is only loaded once during execution) will cause a fatal error to be raised if the file doesn't exist, whereas include
will only raise a warning. See http://php.net/require and http://php.net/include for more details
Include a class example with the use
keyword from Command Line Interface:
PHP Namespaces don't work on the commandline unless you also include or require the php file. When the php file is sitting in the webspace where it is interpreted by the php daemon then you don't need the require line. All you need is the 'use' line.
Create a new directory
/home/el/bin
Make a new file called
namespace_example.php
and put this code in there:<?php require '/home/el/bin/mylib.php'; use foobarwhatever\dingdong\penguinclass; $mypenguin = new penguinclass(); echo $mypenguin->msg(); ?>
Make another file called
mylib.php
and put this code in there:<?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."; } } ?>
Run it from commandline like this:
el@apollo:~/bin$ php namespace_example.php
Which prints:
It's a beautiful day chris, come out and play! NO! *SLAM!* taka taka taka taka
See notes on this in the comments here: http://php.net/manual/en/language.namespaces.importing.php
I suggest you also take a look at __autoload.
This will clean up the code of requires and includes.
require('/yourpath/yourphp.php');
http://php.net/manual/en/function.require.php
require_once('/yourpath/yourphp.php');
http://php.net/manual/en/function.require-once.php
include '/yourpath/yourphp.php';
http://www.php.net/manual/en/function.include.php
use \Yourapp\Yourname
http://php.net/manual/fa/language.namespaces.importing.php
Notes:
Avoid using require_once because it is slow: Why is require_once so bad to use?
Check: http://www.php.net/require and http://www.php.net/include
精彩评论