CONSTANT
static
self
- scope resolution operator
::
Constants are variables that cannot have their values changed during execution. The default visibility of
class constants is public. Constants can be accessed via the scope resolution operator ::
.
<?php
class FileSystem {
const CHMOD_DIRECTORY = 0775;
const CHMOD_FILE = 0664;
public function chmod($uri) {
$mode = is_dir($uri) ? self::CHMOD_DIRECTORY : self::CHMOD_FILE;
if (@chmod($uri, $mode)) {
return TRUE;
}
$this->logger->error('The file permissions could not be set on %uri.', ['%uri' => $uri]);
return FALSE;
}
}
$dir_permissions = FileSystem::CHMOD_DIRECTORY;
Static methods exist only within the scope of the class, not the generated object. The only properties which they can access are properties which are also declared as static properties.
You may have seen the use of static
inside non-object-oriented functions. Static variables keep
their values across multiple function calls.
<?php
function test() {
static $a = 0;
echo $a . PHP_EOL;
$a++;
}
test(); // 0
test(); // 1
test(); // 2
Declaring class properties or methods as static makes them accessible without needing an instantiation of the class.
Attributes or methods declared as static should not be accessed via an instantiated class
object (->
).
<?php
class Url {
public static function fromUri($uri, $options = []) {
// Process $uri and $options and return a Url object.
return $url;
}
public static function fromUserInput($user_input, $options = []) {
return static::fromUri('internal:' . $user_input, $options);
}
}
$url = Url::fromUserInput('/robots.txt');
- Add a static method to the "Person" class that compares two individuals by age and returns the oldest one.
- Call that static method.