在我们继续之前:请养成以下习惯:always指定对象的属性和方法的可见性/可访问性。而不是写作
function foo()
{//php 4 style method
}
Write:
public function foo()
{
//this'll be public
}
protected function bar()
{
//protected, if this class is extended, I'm free to use this method
}
private function foobar()
{
//only for inner workings of this object
}
首先,你的第一个例子A::foo
将触发通知(静态调用非静态方法总是会执行此操作)。
其次,在第二个例子中,当调用A::foo()
,PHP 不会创建即时实例,也不会在您调用时在实例上下文中调用该方法$a->foo()
(顺便说一句,它也会发出通知)。静态本质上是全局函数,因为在内部,PHP 对象只不过是一个 Cstruct
,方法只是具有指向该结构的指针的函数。至少,要点是这样的更多详细信息请点击此处 https://wiki.php.net/internals/engine/objects
静态属性或方法的主要区别(如果使用得当的话会有好处)是,它们在所有实例上共享and全球可访问:
class Foo
{
private static $bar = null;
public function __construct($val = 1)
{
self::$bar = $val;
}
public function getBar()
{
return self::$bar;
}
}
$foo = new Foo(123);
$foo->getBar();//returns 123
$bar = new Foo('new value for static');
$foo->getBar();//returns 'new value for static'
正如你所看到的,静态属性$bar
无法在每个实例上设置,如果更改其值,则更改适用于所有实例。
If $bar
是公共的,你甚至不需要一个实例来改变各处的属性:
class Bar
{
public $nonStatic = null;
public static $bar = null;
public function __construct($val = 1)
{
$this->nonStatic = $val;
}
}
$foo = new Bar(123);
$bar = new Bar('foo');
echo $foo->nonStatic, ' != ', $bar->nonStatic;//echoes "123 != foo"
Bar::$bar = 'And the static?';
echo $foo::$bar,' === ', $bar::$bar;// echoes 'And the static? === And the static?'
查看工厂模式,并且(纯粹提供信息)还查看单例模式。就单例模式而言:还谷歌为什么not使用它。 IoC、DI、SOLID 是您很快就会遇到的缩写词。阅读它们的含义并找出它们(各自以自己的方式)的主要原因not选择单身人士