PHP のオブジェクトとクラスの違いは何ですか? 質問する

PHP のオブジェクトとクラスの違いは何ですか? 質問する

PHP のオブジェクトとクラスの違いは何ですか? 両方の意味がよくわからないので質問します。

違いを教えてください良い例え?

ベストアンサー1

あなたは持っていると思いますマニュアルを読む基本的な PHP OOP について。

クラスとは、定義するオブジェクトのプロパティ、メソッド、動作。オブジェクトはあなたが作ったものクラス外。クラスを青写真、そしてオブジェクトは実際の建物設計図(クラス)に従って構築します。(はい、設計図と建物の類似性は、すでに何度も取り上げられてきました。)

// Class
class MyClass {
    public $var;

    // Constructor
    public function __construct($var) {
        echo 'Created an object of MyClass';
        $this->var = $var;
    }

    public function show_var() {
        echo $this->var;
    }
}

// Make an object
$objA = new MyClass('A');

// Call an object method to show the object's property
$objA->show_var();

// Make another object and do the same
$objB = new MyClass('B');
$objB->show_var();

ここでのオブジェクトは別個ですが (A と B)、どちらもMyClassクラスのオブジェクトです。設計図と建物の例えに戻ると、同じ設計図を使用して 2 つの異なる建物を建てると考えてください。

より文字通りの例が必要な場合、実際に建物について話している別のスニペットを以下に示します。

// Class
class Building {
    // Object variables/properties
    private $number_of_floors = 5; // Each building has 5 floors
    private $color;

    // Constructor
    public function __construct($paint) {
        $this->color = $paint;
    }

    public function describe() {
        printf('This building has %d floors. It is %s in color.', 
            $this->number_of_floors, 
            $this->color
        );
    }
}

// Build a building and paint it red
$bldgA = new Building('red');

// Build another building and paint it blue
$bldgB = new Building('blue');

// Tell us how many floors these buildings have, and their painted color
$bldgA->describe();
$bldgB->describe();

おすすめ記事