2016-09-29 4 views
-4
class User { 

    public $name; 

    public function __construct($name) { 
    $this->name = $name; 
    } 

    public function sayHi() { 
    echo "Hi, I am $this->name!"; 
    } 
} 

$ this-> name = $ nameの意味は何ですか? 私は$ thisが(あらかじめ定義されている=記号)$ name(したがって=記号)の名前に入るように考えています。 また、私はその機能の必要性を見ていませんか?

はちょうどこのように行くことができる:

class User { 

    public $name; 

    public function sayHi() { 
    echo "Hi, I am $name!"; 
    } 
} 

私はこれを考えるアイデアの出てる..事前に感謝を。

+3

'$ this-> name'はクラスプロパティ' $ name'を参照しています。 '$ name'、' __construct'パラメータは単なる変数です。そこで、 '$ name'クラスのプロパティに' __construct'パラメータ '$ name'を代入しています。 '$ this'は現在のクラスを参照します。 '__construct'パラメータ' $ name'は他の名前を持つことができることに注意してください。これは単なるパラメータか簡単な変数です。 '$ this-> name'はクラスプロパティ名を参照します。 [続きを読む](http://php.net/manual/ro/language.oop5.properties.php) – Andrew

+0

ありがとうございます!これは本当に私の理解を明確にするのに役立ちます。再度ありがとう –

答えて

0

あなたはそれがクラスの$nameプロパティに設定されている$this->nameによって__constructパラメータ$name、とクラスUserの新しいインスタンスを作成しています。 2番目の例では、$nameは値が割り当てられていないため、値を取得しません。あなたがより良く理解するために、このようにそれをも持つことができ

class User { 

    public $nameProperty; 

    public function __construct($name) { 
    $this->nameProperty = $name; 
    } 

    public function sayHi() { 
    echo "Hi, I am $this->nameProperty!"; 
    } 
} 

$thisあなたが現在いるクラスを指しますが、Userの新しいクラスを作成するときに、あなたが使用して名前を渡すことができます。 $nameパラメータ。このパラメータは$namePropertyに割り当てられ、メソッドsayHi()では割り当てられた名前がエコーされます。クラスメソッドのコンテキストでは

+0

ありがとう、本当に助ける:) –

0
class User { 

    public $name; //declare a public property 

    public function __construct($name) { 
     $this->name = $name; 
    /* at the time of object creation u have to send the value & that value will be store into a public property which will be available through out the class. like $obj = new User('Harry'); Now this will be set in $this->name & it is available inside any method without declaration. 

    */ 
    } 

    public function sayHi() { 
    echo "Hi, I am $this->name!"; //$this->name is available here 
    } 
} 
0

、あなたはクラスのプロパティにアクセスしたい場合、あなたはます$ this->プロパティを使用する必要があります。 $ thisがなければ、実際にはメソッドのスコープ内の変数にアクセスしています。その場合は、パラメータ$です。

機能__construct()は、あなたのクラスオブジェクトのためのコンストラクタです。したがって、オブジェクトをインスタンス化する場合は、コンストラクタ内でコードを実行します。例:

$user = new User("John"); // you are actually calling the __construct method here 
echo $user->name; // John 

あなたを啓発する希望。

+0

ありがとう!私はそれについて実際には迷っていました!再度、感謝します –

関連する問題