ホームページ  >  記事  >  バックエンド開発  >  PHPオブジェクト指向プログラミングにおけるselfとstaticの違い_phpスキル

PHPオブジェクト指向プログラミングにおけるselfとstaticの違い_phpスキル

WBOY
WBOYオリジナル
2016-05-16 09:00:142721ブラウズ

php オブジェクト指向プログラミングでは、必ずこの問題に遭遇します。

class test{
 public static function test(){
  self::func();

  static::func();
 }

 public static function func(){}
}

しかし、自己と静的の違いを知っていますか?

実際、違いは非常に簡単です。理解するには、いくつかのデモを作成するだけで済みます。

自分用のデモ:

class car
{
 public static function model(){
  self::getmodel();
 }

 protected static function getmodel(){
  echo "this is a car model";
 }
}

car::model();

class taxi extends car
{
 protected static function getmodel(){
  echo "this is a taxi model";
 }
}

タクシー::model();
出力を取得する

this is a car model
this is a car model

self が引き続きサブクラス内の親クラスのメソッドを呼び出すことがわかります。

静的デモ

class car
{
 public static function model(){
  static::getmodel();
 }

 protected static function getmodel(){
  echo "this is a car model";
 }
}

car::model();

class taxi extends car
{
 protected static function getmodel(){
  echo "this is a taxi model";
 }
}

taxi::model();

出力を取得する

This is a car model
This is a Taxi model

静的呼び出しの場合、サブクラスが親クラスのメソッドを呼び出したとしても、親クラスのメソッドで呼び出されるメソッドは依然としてサブクラスのメソッドであることがわかります (非常にわかりにくい...)

php5.3 バージョンより前は、static と self の間にはまだわずかな違いがありました。具体的な違いは何でしたか? 結局、それらはすべてバージョン 7 によって支配されました。もう理解できなくなります。

要約すると、self は現在のクラス内のメソッドのみを参照でき、static キーワードを使用すると、関数は実行時にクラス内のメソッドを動的にバインドできます。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。