【发布时间】:2018-12-02 21:55:00
【问题描述】:
谁能解释为什么我可以在TestFoo::getFooInstance() 中设置私人成员$bar?
TestFoo::getFoo2Instance() 然而返回一个致命错误。
我一直认为私有成员应该只能从同一个对象实例而不是同一个对象类访问?
<?php
class TestFoo {
private $bar;
public static function getFooInstance()
{
$instance = new TestFoo();
$instance->bar = "To bar or not to bar";
return $instance;
}
public static function getFoo2Instance()
{
$instance = new TestFoo2();
$instance->bar = "To bar or not to bar";
return $instance;
}
public function getBar()
{
return $this->bar;
}
}
class TestFoo2 {
private $bar;
public function getBar()
{
return $this->bar;
}
}
$testFoo = TestFoo::getFooInstance();
echo $testFoo->getBar();
// returns PHP fatal error
//$testFoo2 = TestFoo::getFoo2Instance();
//echo $testFoo2->getBar();
?>
【问题讨论】:
-
我一直对同样的事情感到困惑,但似乎需要这样才能在类中有不同的实例,或者实现单例
标签: php