
Untitled
By: a guest on
Apr 26th, 2012 | syntax:
None | size: 1.04 KB | hits: 13 | expires: Never
Is it possible to get the current class instance from a static class method?
class C{
function static getInstance(){
// here
}
}
$c = new c;
print_r(C::getInstance()); // should be $c
print_r($c::getInstance()); // should be $c
class C {
private static $instance;
public static function getInstance(){
return self::$instance;
}
public function __construct() {
self::$instance = $this;
}
}
$c = new c;
print_r(C::getInstance()); // should be $c
class C
{
private static $instance;
public static function getInstance()
{
if (!is_null(self::$instance)) return self::$instance;
self::$instance = new self;
return self::$instance;
}
private function __construct()
{
// Whatever
}
}
$c = new C; // This will not work since __construct() is private
$c1 = C::getInstance();
$c2 = C::getInstance();
echo ($c1 == $c2 ? 'yes' : 'no'); // yes
<?php
class CallableClass
{
public function __invoke()
{
return this;
}
}
$obj = new CallableClass;
var_dump($obj);