Voting

: nine minus eight?
(Example: nine)

The Note You're Voting On

5imun at github dot com
2 years ago
You must be careful when getting static property of extended class from parent class, in example below you can see that using property_exists (method getA2) instead of isset with static keyword (method getA1) to check if the static property exist gives much more intuitive result:

<?php
class Foo
{
public static
string $A;

public static function
init() {
return static::class;
}

public static function
getA1() {
if (!isset(static::
$A)) {
static::
$A = static::class;
}
return static::
$A;
}

public static function
getA2() {
if (
property_exists(static::class, 'A')) {
static::
$A = static::class;
}
return static::
$A;
}
}
class
Bar extends Foo {}

$foo = new Foo();
echo
$foo->getA1();
echo
$foo->getA2();
echo
$foo->getA1();

$bar = new Bar();
echo
$bar->getA1();
echo
$bar->getA2();
echo
$bar->getA1();
?>

Output:
Foo
Foo
Foo

Foo
Bar
Bar

Notice how $bar->getA1() returns "Foo" instead of "Bar" that many people would expect to see.

<< Back to user notes page

To Top