Skip to content

Commit fcba8bf

Browse files
authored
Merge pull request #1 from php-elementary/late-static
Late static binding
2 parents 7c0b106 + 6acfecd commit fcba8bf

2 files changed

Lines changed: 22 additions & 11 deletions

File tree

src/SingletonTrait.php

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,20 @@
66
trait SingletonTrait
77
{
88
/**
9-
* @var self
9+
* @var static
1010
*/
1111
protected static $instance = null;
1212

1313
/**
14-
* @return self
14+
* @return static
1515
*/
1616
public static function me()
1717
{
18-
if (self::$instance === null) {
19-
self::$instance = new self();
18+
if (static::$instance === null) {
19+
static::$instance = new static();
2020
}
2121

22-
return self::$instance;
22+
return static::$instance;
2323
}
2424

2525
}

tests/SingletonTraitTest.php

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,18 +27,29 @@ public function me()
2727
{
2828
fwrite(STDOUT, "\n". __METHOD__);
2929

30-
$firstInstance = Singleton::me();
31-
$secondInstance = Singleton::me();
30+
$mock = $this->buildMock();
3231

33-
$this->assertEquals(get_class($firstInstance), get_class($secondInstance));
32+
$this->assertEquals(get_class($mock::me()), get_class($mock::me()));
3433

35-
$str = 'should exists in next getInstance()';
36-
$firstInstance->fooBar = $str;
37-
$this->assertEquals($str, $secondInstance->fooBar);
34+
$this->assertNotEquals(Singleton::class, get_class(SingletonCh2::me()));
35+
$this->assertEquals(get_class(Singleton::me()), SingletonCh2::class);
36+
37+
$this->assertNotEquals(get_class(Singleton::me()), get_class(SingletonCh1::me()));
38+
$this->assertEquals(SingletonCh1::class, get_class(SingletonCh1::me()));
3839
}
3940
}
4041

4142
class Singleton
4243
{
4344
use SingletonTrait;
45+
}
46+
47+
class SingletonCh1 extends Singleton
48+
{
49+
protected static $instance = null;
50+
}
51+
52+
class SingletonCh2 extends Singleton
53+
{
54+
4455
}

0 commit comments

Comments
 (0)