Introduction to the use of class level constants in php5.5

  • 2020-10-23 20:03:29
  • OfStack

php recently released the first stable version of 5.5, introducing a class-level constant named 'CLASS' which is valid for all classes and returns the full name of the class.


<?php 
namespace vendorpackage; 
class Foo 
{ 
    // ... 
} 
var_dump(Foo::CLASS); 
// Above script output  string(18) "vendorpackageFoo".

Why use it

Why do we use a constant like this, not just to get the full name of the class as in example 1 above? ___ We can get the same effect by using ___ 10EN__ and with php5.3 should be fine:

 
<?php 
namespace vendorpackage; 
class Foo 
{ 
    // ... 
} 
var_dump(__NAMESPACE__ . 'Foo');

However, when you need to fully qualify the name, the namespace references the class namespace alias... Then it gets interesting.

Here are some examples:


<?php 
use vendorpackageFoo; 
class FooTest extends PHPUnit_Framework_TestCase 
{ 
    public function testBarCanBeProcessed() 
    { 
        $bar = $this->getMock('vendorpackageBar'); 
        $foo = new Foo; 
        $foo->process($bar); 
        // ... 
    } 
}


<?php 
use vendorpackageFoo; 
use vendorpackageBar; 
class FooTest extends PHPUnit_Framework_TestCase 
{ 
    public function testBarCanBeProcessed() 
    { 
        $bar = $this->getMock(Bar::CLASS); 
        $foo = new Foo; 
        $foo->process($bar); 
        // ... 
    } 
}  


Related articles: