Skip to content

Instantly share code, notes, and snippets.

@alan-ps
Last active May 30, 2019 07:40
Show Gist options
  • Save alan-ps/572972ce4d5f2b75b4fe0d02aa07aa81 to your computer and use it in GitHub Desktop.
Save alan-ps/572972ce4d5f2b75b4fe0d02aa07aa81 to your computer and use it in GitHub Desktop.

Overview

The keyword static is similar to self, except, that it related to a class which calls a method and do not related to a class which contains a call.

Example

<?php
  
abstract class Drink {
  private $category;

  public function __construct() {
    $this->category = static::getCategory();
  }
  
  public static function create() {
    return new static();
  }
  
  public static function getCategory() {
    return 'default';
  }
}

class Water extends Drink {}

class Beer extends Drink {
  public static function getCategory() {
    return 'alcohol';
  }
}

class CraftBeer extends Beer {}

print_r(Water::create()); // Water Object([category:Drink:private] => default)
print_r(CraftBeer::create()); // CraftBeer Object([category:Drink:private] => alcohol)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment