0

私は PHP5 の OOP スタイルに慣れていませんが、サンプル クラスとプロダクション クラスの中で気づき__constructまし__deconstructた。

私はこれのマニュアルを読みました:

http://php.net/manual/en/language.oop5.decon.php

そして、StackOverflow に関する一連の質問/回答に目を通しました。その存在の実際の意味が何であるかを理解するのにまだ苦労していますか?

class foo {
   function __construct()
   {
     // do something 
   }

   public function Example ()
   {
    echo "Example Functions";
   }

   function __destruct()
   {
     // do something
   }
}

同じクラスは、次のようにヒットなしで同じように機能できます。

class foo {
       public function Example ()
       {
        echo "Example Functions";
       }
    }

しかし、マニュアルには上記の例で、私の最初の関数が__construct

これが PHP5 OOP クラス内で優先されるのはなぜですか?

4

3 に答える 3

1

__分解する

クラスがガベージ コレクションされる直前にデストラクタが呼び出され、クラスが破棄される前に直前の操作を実行できます。

_contructor は単なる反対です。オブジェクトの作成中にオブジェクトにプロパティを設定できます。

これは、コンストラクターを作成する古い方法であり、ドキュメントによると、下位互換性のために残されていました。

public function Example ()
{
  echo "Example Functions";
}

「下位互換性のために、PHP 5 が特定のクラスの __construct() 関数を見つけることができず、クラスが親クラスから継承していない場合、クラスの名前で古いスタイルのコンストラクター関数を検索します。事実上、互換性の問題が発生する唯一のケースは、異なるセマンティクスに使用される __construct() という名前のメソッドがクラスにある場合のみであることを意味します。」

http://php.net/manual/en/language.oop5.decon.php

于 2013-03-29T01:38:48.543 に答える
1
class Foo {
    public function __construct() {
        print("This is called when a new object is created");
        // Good to use when you need to set initial values,
        // (possibly) create a connection to a database or such.
    }

    public function __destruct() {
        print("This is called when the class is removed from memory.");
        // Should be used to clean up after yourself, close connections and such.
    }
}

$foo = new Foo();

添加、

class Person {

    private $name; // Instance variable
    private $status; // Instance variable

    // This will be called when a new instance of this class i created (constructed)
    public function __construct($name, $age) {
        $this->name = ucfirst($name); // Change input to first letter uppercase.

        // Let the user of our class input something he is familiar with,
        // then let the constructor take care of that data in order to fit
        // our specific needs.
        if ($age < 20) {
            $this->status = 'Young';
        } else {
            $this->status = 'Old';
        }
    }

    public function printName() {
        print($this->name);
    }

    public function printStatus() {
        print($this->status);
    }
}

$Alice = new Person('alice', 27);
$Alice->printName();
$Alice->printStatus();

/添加

上記のコードを実行してコメントを読むと、コンストラクタとデストラクタをいつ、どのように使用する必要があるかを理解できるはずです。

于 2013-03-29T01:41:49.023 に答える
0

クラスはtypeを定義することを理解する必要があります。これは、データの種類とそのデータに対して実行できる操作の両方を意味します。そのデータはメンバー変数として内部的に保存されます。同様に、これらの操作はクラスのメソッドによって定義されます。コンストラクターは、オブジェクトの初期内部状態 (つまり、そのメンバー変数と内部操作) を初期化するために使用されます。

PHP のデストラクタは、通常、手動でオブジェクトをクリーンアップするために使用されます。PHP のファイア アンド フォーゲットの性質により、これらはそれほど頻繁には使用されません。これらは、実行時間の長いスクリプトでリソース (db 接続、ファイル ハンドル) を解放するために使用される場合があります。

于 2013-03-29T01:49:23.930 に答える