Skip to content

Instantly share code, notes, and snippets.

@adam000
Last active July 26, 2016 15:53
Show Gist options
  • Save adam000/39451537b2afe2a60d87ef58e1c39fe5 to your computer and use it in GitHub Desktop.
Save adam000/39451537b2afe2a60d87ef58e1c39fe5 to your computer and use it in GitHub Desktop.
A small test to see what gets returned for the various "I want to know what class I'm in" patterns in PHP
<?php
class base {
static function whoami_static() {
echo('__CLASS__: ' . __CLASS__ . "\n");
echo('get_class(): ' . get_class() . "\n");
echo('get_called_class(): ' . get_called_class() . "\n");
echo('static::class: ' . static::class . "\n");
}
function whoami() {
echo('__CLASS__: ' . __CLASS__ . "\n");
echo('get_class(): ' . get_class() . "\n");
echo('get_called_class(): ' . get_called_class() . "\n");
echo('static::class: ' . static::class . "\n");
}
}
class derived extends base {
function whoami() {
parent::whoami();
echo('-----------' . "\n");
echo('__CLASS__: ' . __CLASS__ . "\n");
echo('get_class(): ' . get_class() . "\n");
echo('get_called_class(): ' . get_called_class() . "\n");
echo('static::class: ' . static::class . "\n");
}
}
base::whoami_static();
// Output:
// __CLASS__: base
// get_class(): base
// get_called_class(): base
// static::class: base
derived::whoami_static();
// Output:
// __CLASS__: base
// get_class(): base
// get_called_class(): derived
// static::class: derived
$base = new base();
$base->whoami();
// Output:
// __CLASS__: base
// get_class(): base
// get_called_class(): base
// static::class: base
$derived = new derived();
$derived->whoami();
// Output:
// __CLASS__: base
// get_class(): base
// get_called_class(): derived
// static::class: derived
// -----------
// __CLASS__: derived
// get_class(): derived
// get_called_class(): derived
// static::class: derived
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment