Skip to content

Latest commit

 

History

History
93 lines (63 loc) · 2.01 KB

4.md

File metadata and controls

93 lines (63 loc) · 2.01 KB

Lesson 4: Constants, and Static Properties/Methods

New Keywords:

  • CONSTANT
  • static
  • self
  • scope resolution operator ::

Constants

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

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.

Not Static Variables

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

Static Keyword in Classes

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');

Exercise:

  1. Add a static method to the "Person" class that compares two individuals by age and returns the oldest one.
  2. Call that static method.