Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^48) CHAPTER 5 ■ WHAT'S NEW IN PHP 6
Listing 5-9. Scope Resolution for Namespaces
<?php
require_once('Vector.php');
$line = new Vector::Line();
$line->draw(1,1,10,10);
You can use multiple levels of namespaces. For example, Graphics::Vector::Line is valid
as a namespace name. The only restriction is that you may have only one namespace declara-
tion per file.
As the namespace size grows, using namespaces can become a bit verbose. Fortunately,
PHP also provides the use statement, which allows you to alias a specific namespace. Listing 5-10
shows how to use the use statement to shorten the instantiation of the Line class.
Listing 5-10. Using the use Statement
<?php
require_once('Vector.php');
use Vector::Line as Line;
$line = new Line();
$line->draw(1,1,10,10);
You can also alias an entire namespace with the use statement.


Late Static Binding


It has been a long-standing issue with PHP’s inheritance model that a parent class could not
easily reference the final state of the class when extended. Consider the example shown in
Listing 5-11.

Listing 5-11. Unintended Inheritance

<?php
class ParentBase {
static $property = 'Parent Value';
public static function render() {
return self::$property;
}
}
class Descendant extends ParentBase {
static $property = 'Descendant Value';
}
echo Descendant::render();

McArthur_819-9C05.fm Page 48 Wednesday, February 27, 2008 8:38 AM

Free download pdf