php5.5中类级别的常量使用介绍_php基础
May 17, 2016 am 08:59 AM不久前php刚发布了5.5的第一个稳定版,介绍了一个类级别的常量,名字是 `CLASS` 这个常量对所有的类有效,返回类的全名。
namespace vendorpackage;
class Foo
{
// ...
}
var_dump(Foo::CLASS);
//上面脚本输出 string(18) "vendorpackageFoo".
为什么要使用它
我们为什么要使用一个这样的常量,当然不是像上面那个例子一样只是获得类的全名。我们使用__NAMESPACE__也可以达到同样的效果,而且php5.3就可以用了:
namespace vendorpackage;
class Foo
{
// ...
}
var_dump(__NAMESPACE__ . 'Foo');
然而,当你需要完全限定名称,命名空间引用了类命名空间别名…然后它变得有趣。
在下面的例子:
use vendorpackageFoo;
class FooTest extends PHPUnit_Framework_TestCase
{
public function testBarCanBeProcessed()
{
$bar = $this->getMock('vendorpackageBar');
$foo = new Foo;
$foo->process($bar);
// ...
}
}
use vendorpackageFoo;
use vendorpackageBar;
class FooTest extends PHPUnit_Framework_TestCase
{
public function testBarCanBeProcessed()
{
$bar = $this->getMock(Bar::CLASS);
$foo = new Foo;
$foo->process($bar);
// ...
}
}

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

What are constants in C language? Can you give an example?

In Java, is it possible to define a constant using only the final keyword?

PHP error: How to solve the problem when calling undefined constant?

PHP error: What should I do if I use an undefined constant as a property name?

Definition and initialization methods of basic data type constants study guide

FILTER_SANITIZE_SPECIAL_CHARS constant in PHP

Naming conventions in PHP: How to name constants and file names using underscore nomenclature
