[英]static method vs non-static method
以下是靜態方法和非靜態方法的php類代碼示例。
范例1:
class A{
//None Static method
function foo(){
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")<br>";
} else {
echo "\$this is not defined.<br>";
}
}
}
$a = new A();
$a->foo();
A::foo();
//result
$this is defined (A)
$this is not defined.
范例2:
class A{
//Static Method
static function foo(){
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")<br>\n";
} else {
echo "\$this is not defined.<br>\n";
}
}
}
$a = new A();
$a->foo();
A::foo();
//result
$this is not defined.
$this is not defined.
我試圖找出這兩個類之間的區別。
正如我們在非靜態方法的結果中看到的那樣,定義了“ $ this”。
但是另一方面,即使靜態方法都被實例化,也沒有定義靜態方法的結果。
我想知道為什么自從將它們都實例化后它們會有不同的結果?
您能給我啟發一下這些代碼上發生了什么。
我們繼續之前:請進入的總是你指定對象的屬性和方法的可見性/可訪問的習慣中。 而不是寫作
function foo()
{//php 4 style method
}
寫:
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()
時,它也不會在實例的上下文中調用該方法。 $a->foo()
(還會發出BTW通知)。 靜態從本質上講是全局函數,因為在內部,PHP對象不過是C struct
,而方法只是具有指向該結構的指針的函數。 至少這就是要點, 更多細節在這里
靜態屬性或方法的主要區別(如果使用得當,則有好處)是它們在所有實例之間共享並且可以全局訪問:
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
,如果更改了其值,則該更改將應用於所有實例。
如果$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?'
查看工廠模式,並(純粹提供信息)也查看Singleton模式。 就Singleton模式而言:此外,google為什么不使用它。 IoC,DI,SOLID是您很快會遇到的縮寫。 了解它們的含義,並弄清楚為什么他們(以自己的方式)是不選擇Singletons的主要原因
有時您需要使用一種方法,但是卻不想調用類,因為類中的某些函數會自動調用,例如__construct,__ destruct,...(魔術方法)。
叫課:
$a = new A();
$a->foo();
不要調用class :(只需運行foo()函數)
A::foo();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.