Skip to content

Instantly share code, notes, and snippets.

@phptek
Created May 24, 2016 09:09
Show Gist options
  • Save phptek/fa3de7494a8fee4f91f62b687e0d51a5 to your computer and use it in GitHub Desktop.
Save phptek/fa3de7494a8fee4f91f62b687e0d51a5 to your computer and use it in GitHub Desktop.
Various uses of PHP's "static" keyword.
PHP's "statics"
1. Static methods within a class.
Note: Allows dev's to encapsulate similar methods within a class, but with the "benefit" of easy access by means of global scope.
Reference: http://php.net/manual/en/language.oop5.static.php
Example:
class Foo
{
public static function a_static_method()
{
echo 'Hi!';
}
}
<?php
Foo::a_static_method(); // Prints "Hi!";
2. Static variables
Note: PHP creates an internal memory pointer to the variable marked as static. This means it will survive multiple page reloads giving developer's a little state within a stateless environment (HTTP)
Reference: http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static
Example:
<?php
function foo()
{
static $a = 0;
return $a++;
}
echo foo(); // Prints 0, then after reload 1, then 2 (etc)
3. LSB (Late Static Binding)
Note: Allows dev's to define which class should be referred-to by subclasses; One of the base class or the subclass.
Reference: http://php.net/manual/en/language.oop5.late-static-bindings.php
Example: (See reference page)
Note also the use of `new static()` which allows instantiating classes within static methods.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment