PHP lets you access properties or methods without having to create an instance of the class. The keyword used for this purpose is static.
static keyword after stating the visibility level when declaring an ordinary property or method. Use the self keyword to reference the property internally:class Test
{
public static $test = 'TEST';
public static function getTest()
{
return self::$test;
}
}self keyword will bind early, which will cause problems when accessing static information in child classes. If you absolutely need to access information from the child class, use the static keyword in place of self. This process is referred to as Late Static Binding.Child::getEarlyTest(), the output will be TEST. If, on the other hand, you run Child::getLateTest(), the output will be CHILD. The reason is that PHP will bind to the earliest definition when using self, whereas the latest binding is used for the static keyword:class Test2
{
public static $test = 'TEST2';
public static function getEarlyTest()
{
return self::$test;
}
public static function getLateTest()
{
return static::$test;
}
}
class Child extends Test2
{
public static $test = 'CHILD';
}factory() is defined which returns a PDO connection:public static function factory(
$driver,$dbname,$host,$user,$pwd,array $options = [])
{
$dsn = sprintf('%s:dbname=%s;host=%s',
$driver, $dbname, $host);
try {
return new PDO($dsn, $user, $pwd, $options);
} catch (PDOException $e) {
error_log($e->getMessage);
}
}You can reference static properties and methods using the class resolution operator "::". Given the Test class shown previously, if you run this code:
echo Test::$test; echo PHP_EOL; echo Test::getTest(); echo PHP_EOL;
You will see this output:

To illustrate Late Static Binding, based on the classes Test2 and Child shown previously, try this code:
echo Test2::$test; echo Child::$test; echo Child::getEarlyTest(); echo Child::getLateTest();
The output illustrates the difference between self and static:

Finally, to test the factory() method shown previously, save the code into the Application\Database\Connection class in a Connection.php file in the Application\Database folder. You can then try this:
include __DIR__ . '/../Application/Database/Connection.php';
use Application\Database\Connection;
$connection = Connection::factory(
'mysql', 'php7cookbook', 'localhost', 'test', 'password');
$stmt = $connection->query('SELECT name FROM iso_country_codes');
while ($country = $stmt->fetch(PDO::FETCH_COLUMN))
echo $country . '';You will see a list of countries pulled from the sample database:

For more information on Late Static Binding, see this explanation in the PHP documentation:
http://php.net/manual/en/language.oop5.late-static-bindings.php