Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
object が同一かどうかはspl_object_hashで見ている http://php.net/manual/ja/function.spl-object-hash.php
<?php
class A {
protected static $foo = null;
function hoge() {
if (is_null(self::$foo)) {
self::$foo = new Inner();
}
return self::$foo;
}
}
class B extends A {
//protected static $foo = null;
function hoge() {
if (is_null(self::$foo)) {
self::$foo = new Inner();
}
self::$foo->bar = 'hogehoge';
return self::$foo;
}
}
class Inner {
public $bar = null;
}
$a = new A();
$b = new B();
echo spl_object_hash($a->hoge()) . "\n";
var_dump($a->hoge());
echo spl_object_hash($b->hoge()) . "\n";
var_dump($b->hoge());
echo spl_object_hash($a->hoge()) . "\n";
var_dump($a->hoge());
/*
0000000019cce013000000005e2dcd60
object(Inner)#3 (1) {
["bar"]=>
NULL
}
0000000019cce013000000005e2dcd60
object(Inner)#3 (1) {
["bar"]=>
string(8) "hogehoge"
}
0000000019cce013000000005e2dcd60
object(Inner)#3 (1) {
["bar"]=>
string(8) "hogehoge"
}
*/
<?php
class A {
protected static $foo = null;
function hoge() {
if (is_null(self::$foo)) {
self::$foo = new Inner();
}
return self::$foo;
}
}
class B extends A {
protected static $foo = null;
function hoge() {
if (is_null(self::$foo)) {
self::$foo = new Inner();
}
self::$foo->bar = 'hogehoge';
return self::$foo;
}
}
class Inner {
public $bar = null;
}
$a = new A();
$b = new B();
echo spl_object_hash($a->hoge()) . "\n";
var_dump($a->hoge());
echo spl_object_hash($b->hoge()) . "\n";
var_dump($b->hoge());
echo spl_object_hash($a->hoge()) . "\n";
var_dump($a->hoge());
/*
0000000056b6bba5000000000c16550c
object(Inner)#3 (1) {
["bar"]=>
NULL
}
0000000056b6bba2000000000c16550c
object(Inner)#4 (1) {
["bar"]=>
string(8) "hogehoge"
}
0000000056b6bba5000000000c16550c
object(Inner)#3 (1) {
["bar"]=>
NULL
}
*/
<?php
class A {
protected static $foo = null;
function hoge() {
if (is_null(self::$foo)) {
self::$foo = new Inner();
}
return self::$foo;
}
}
class Inner {
public $bar = null;
}
class B extends A {
protected static $foo = null;
function hoge() {
if (is_null(parent::$foo)) {
parent::$foo = new Inner();
}
parent::$foo->bar = 'hogehoge';
return parent::$foo;
}
}
$a = new A();
$b = new B();
echo spl_object_hash($a->hoge()) . "\n";
var_dump($a->hoge());
echo spl_object_hash($b->hoge()) . "\n";
var_dump($b->hoge());
echo spl_object_hash($a->hoge()) . "\n";
var_dump($a->hoge());
/*
7b10dcffee174901c4dbe3b177cd7371
class Inner#3 (1) {
public $bar =>
NULL
}
7b10dcffee174901c4dbe3b177cd7371
class Inner#3 (1) {
public $bar =>
string(8) "hogehoge"
}
7b10dcffee174901c4dbe3b177cd7371
class Inner#3 (1) {
public $bar =>
string(8) "hogehoge"
}
*/
Owner

gom commented Oct 20, 2013

self の static 変数を定義すると、parent と self の同名変数が別のものとなるだけだったもよう。

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