$this, self::, static::

Пример:
Переменную $this можно расшифровать как «в этом классе». ⇓
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<?php /** * Main class for the theme. */ class Theme { /** * Constructor. */ public function __construct( array $components = array() ) { spl_autoload_register( array( $this, 'autoload' ) ); if ( empty( $components ) ) { $components = $this->get_default_components(); } // Set the components. foreach ( $components as $component ) { // Bail if a component is invalid. if ( ! $component instanceof Component_Interface ) { throw new InvalidArgumentException( sprintf( /* translators: 1: classname/type of the variable, 2: interface name */ __( 'The theme component %1$s does not implement the %2$s interface.', 'kadence' ), gettype( $component ), Component_Interface::class ) ); } $this->components[ $component->get_slug() ] = $component; } // Instantiate the template tags instance for all theme templating components. $this->template_tags = new Template_Tags( array_filter( $this->components, function( Component_Interface $component ) { return $component instanceof Templating_Component_Interface; } ) ); } |
Простое использование self:: ⇓
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<?php /** * Kadence\Theme class */ namespace Kadence; use InvalidArgumentException; class Theme { private static $instance = null; public $components = array(); protected $template_tags; public static function instance() { // Return if already instantiated. if ( self::is_instantiated() ) { return self::$instance; } // Setup the singleton. self::setup_instance(); self::$instance->initialize(); // Return the instance. return self::$instance; } private static function setup_instance() { self::$instance = new Theme(); } private static function is_instantiated() { // Return true if instance is correct class. if ( ! empty( self::$instance ) && ( self::$instance instanceof Theme ) ) { return true; } // Return false if not instantiated correctly. return false; } |
$self используется в том, же самом ключе, что и $this, но уже для СТАТИЧЕСКИХ свойств:
Простое использование static:: ⇓
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php class A { public static function who() { echo __CLASS__; } public static function test() { static::who(); // Здесь действует позднее статическое связывание } } class B extends A { public static function who() { echo __CLASS__; } } B::test(); ?> |
Результат выполнения данного примера: B