So I recently ran across a code segment like this:
private static function FOO() {
static $c = null;
if ($c == null) {
$c = new ParentClass_InnerClass();
}
return $c;
}
So what is up with this code? How is this different from:
private static $C;
//other methods and fields
private static function FOO() {
if(!$self::c) {
$self::c = new ParentClass_InnerClass();
}
return $self::c;
}
Or are they even the same concept?
They are, essentially, the same concept, though the scope is different:
class Foobar
{
private static $c = null;
public static function FOO()
{
if (self::$c === null)
{
self::$c = new stdClass;
}
return self::$c;
}
public static function checkC()
{
if (self::$c === null)
{
return false;
}
return self::$c;
}
}
Foobar::checkC();//returns false, as $c is null
//function checkC has access to $c
$returned = Foobar::FOO();//returns object
if ($returned === Foobar::checkC())
{//will be true, both reference the same variable
echo 'The same';
}
Whereas, if we were to change the code to:
class Foobar
{
public static function FOO()
{
static $c = null;
if ($c === null)
{
$c = new stdClass;
}
return $c;
}
public static function checkC()
{
if ($c === null)
{
return false;
}
return $c;
}
}
We will get a notice when calling checkC
: undefined variable. the static variable $c is only accessible from within the FOO
scope. A private property is scoped within the entire class. That's it really.
But really, do yourself a favour: only use statics if you need them (they're shared between instances, too). And in PHP, it's very rare you'll actually need a static.
They're the same concept, except that in the first code block, the static variable is local to the function, and such a static variable could be used in any function, even outside the context of a class:
function test() {
static $counter = 0;
return $counter++;
}
echo test(); // 0
echo test(); // 1
In the top example you can access $c
only from the local scope (FOO()
) and in the bottom example you can access $c
from the entire class, so not only form FOO()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With