锟斤拷锟斤拷锟秸硷拷投锟教拷锟斤拷锟斤拷锟斤拷锟�

(PHP 5 >= 5.3.0, PHP 7)

PHP 锟斤拷锟斤拷锟秸硷拷锟绞碉拷锟斤拷艿锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟侥讹拷态锟斤拷锟斤拷锟斤拷影锟届。锟斤拷耍锟斤拷锟斤拷要锟斤拷锟斤拷锟斤拷拇锟斤拷锟阶拷锟斤拷锟斤拷锟斤拷锟斤拷占锟斤拷校锟�

Example #1 锟斤拷态锟斤拷锟斤拷元锟斤拷

example1.php:

<?php
class classname
{
    function 
__construct()
    {
        echo 
__METHOD__,"\n";
    }
}
function 
funcname()
{
    echo 
__FUNCTION__,"\n";
}
const 
constname "global";

$a 'classname';
$obj = new $a// prints classname::__construct
$b 'funcname';
$b(); // prints funcname
echo constant('constname'), "\n"// prints global
?>
锟斤拷锟斤拷使锟斤拷锟斤拷全锟睫讹拷锟斤拷锟狡o拷锟斤拷锟斤拷锟斤拷锟斤拷锟秸硷拷前缀锟斤拷锟斤拷锟斤拷锟狡o拷锟斤拷注锟斤拷锟斤拷为锟节讹拷态锟斤拷锟斤拷锟斤拷锟狡★拷锟斤拷锟斤拷锟斤拷锟狡伙拷锟斤拷锟斤拷锟斤拷锟叫o拷锟睫讹拷锟斤拷锟狡猴拷锟斤拷全锟睫讹拷锟斤拷锟斤拷没锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟角帮拷锟斤拷姆锟叫憋拷锟斤拷遣锟斤拷锟揭拷摹锟�

Example #2 锟斤拷态锟斤拷锟斤拷锟斤拷锟斤拷锟秸硷拷锟皆拷锟�

<?php
namespace namespacename;
class 
classname
{
    function 
__construct()
    {
        echo 
__METHOD__,"\n";
    }
}
function 
funcname()
{
    echo 
__FUNCTION__,"\n";
}
const 
constname "namespaced";

include 
'example1.php';

$a 'classname';
$obj = new $a// prints classname::__construct
$b 'funcname';
$b(); // prints funcname
echo constant('constname'), "\n"// prints global

/* note that if using double quotes, "\\namespacename\\classname" must be used */
$a '\namespacename\classname';
$obj = new $a// prints namespacename\classname::__construct
$a 'namespacename\classname';
$obj = new $a// also prints namespacename\classname::__construct
$b 'namespacename\funcname';
$b(); // prints namespacename\funcname
$b '\namespacename\funcname';
$b(); // also prints namespacename\funcname
echo constant('\namespacename\constname'), "\n"// prints namespaced
echo constant('namespacename\constname'), "\n"// also prints namespaced
?>

锟斤拷一锟斤拷锟斤拷锟斤拷锟斤拷锟侥讹拷 锟斤拷锟街凤拷锟斤拷锟叫碉拷锟斤拷锟斤拷锟秸硷拷锟斤拷锟斤拷转锟斤拷锟阶拷锟�.