Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 5 ■ WHAT'S NEW IN PHP 6^49

Parent Value

In this example, the render() method refers to self, which is ParentBase and not Descendant.
There is no way from ParentBase::render() to refer to the final value of $property. To solve this
problem, you would need to override the render() method in the descendant class as well.
With the introduction of late static binding, you can now use the scope keyword static to
refer to the final value of a class property or method, as shown in Listing 5-12.

Listing 5-12. Using Static Scope

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

Descendant Value

By using the static scope, you force PHP to look at the final class for all its property values.
In addition to this late binding behavior, PHP also adds the get_called_class() function, which
allows you to determine from which descendant class an inherited method was called. Listing 5-13
shows how you can get the current class calling context using get_called_class().

Listing 5-13. Using get_called_class()

<?php
class ParentBase {
public static function render() {
return get_called_class();
}
}
class Decendant extends ParentBase {}

echo Descendant::render();

Descendant

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

Free download pdf