Skip to content

Instantly share code, notes, and snippets.

@gabesullice
Last active June 26, 2023 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabesullice/543d89c33cc569d69cd9518659223166 to your computer and use it in GitHub Desktop.
Save gabesullice/543d89c33cc569d69cd9518659223166 to your computer and use it in GitHub Desktop.
self vs static vs $this
<?php
class ParentClass {
public static string $foo = 'ooh';
public string $bar = 'lala';
public function __construct($arg) {
$this->bar = $arg;
}
public function dump(): void {
printf(
"Class: %s\nself::\$foo: %s\nstatic::\$foo: %s\n\$this::\$foo: %s\n\$this->bar: %s" . PHP_EOL,
static::class,
self::$foo,
static::$foo,
$this::$foo,
$this->bar,
);
}
}
class ChildClass extends ParentClass {
public static string $foo = 'ahh';
public string $bar = 'haha';
}
$parent = new ParentClass('parent');
$child = new ChildClass('child');
$parent->dump();
echo PHP_EOL;
$child->dump();
echo PHP_EOL;
echo "Setting ParentClass::\$foo = 'hmm'" . PHP_EOL;
ParentClass::$foo = 'hmm';
echo PHP_EOL;
$parent->dump();
echo PHP_EOL;
$child->dump();
@gabesullice
Copy link
Author

gabesullice commented Jun 26, 2023

Prints:

Class: ParentClass
self::$foo: ooh
static::$foo: ooh
$this::$foo: ooh
$this->bar: parent

Class: ChildClass
self::$foo: ooh
static::$foo: ahh
$this::$foo: ahh
$this->bar: child

Setting ParentClass::$foo = 'hmm'

Class: ParentClass
self::$foo: hmm
static::$foo: hmm
$this::$foo: hmm
$this->bar: parent

Class: ChildClass
self::$foo: hmm
static::$foo: ahh
$this::$foo: ahh
$this->bar: child

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment