私は$this
常に PHP で変数を目にしますが、それが何に使用されているのかわかりません。個人的に使ったことはありません。
$this
変数が PHP でどのように機能するか教えてもらえますか?
これは現在のオブジェクトへの参照であり、オブジェクト指向コードで最も一般的に使用されます。
例:
<?php
class Person {
public $name;
function __construct( $name ) {
$this->name = $name;
}
};
$jack = new Person('Jack');
echo $jack->name;
これにより、「Jack」文字列が作成されたオブジェクトのプロパティとして保存されます。
$this
は、さまざまなコンテキストでインタープリターに対して試してみることです。print isset($this); //true, $this exists
print gettype($this); //Object, $this is an object
print is_array($this); //false, $this isn't an array
print get_object_vars($this); //true, $this's variables are an array
print is_object($this); //true, $this is still an object
print get_class($this); //YourProject\YourFile\YourClass
print get_parent_class($this); //YourBundle\YourStuff\YourParentClass
print gettype($this->container); //object
print_r($this); //delicious data dump of $this
print $this->yourvariable //access $this variable with ->
したがって、$this
疑似変数には現在のオブジェクトのメソッドとプロパティがあります。このようなことは、クラス内のすべてのメンバー変数とメンバー メソッドにアクセスできるため便利です。例えば:
Class Dog{
public $my_member_variable; //member variable
function normal_method_inside_Dog() { //member method
//Assign data to member variable from inside the member method
$this->my_member_variable = "whatever";
//Get data from member variable from inside the member method.
print $this->my_member_variable;
}
}
$this
Object
変数の配列を含む、インタープリターによって作成された PHP への参照です。
$this
通常クラスの通常メソッド内で呼び出すと$this
、そのメソッドが属するオブジェクト (クラス) が返されます。
$this
コンテキストに親オブジェクトがない場合、未定義になる 可能性があります。
php.net には、PHP オブジェクト指向プログラミングと$this
コンテキストに応じた動作について説明している大きなページがあります。
https://www.php.net/manual/en/language.oop5.basic.php
これは、他の多くのオブジェクト指向言語と同じように、クラスのインスタンスをそれ自体から参照する方法です。
PHPドキュメントから:
疑似変数 $this は、メソッドがオブジェクト コンテキスト内から呼び出されたときに使用できます。$this は、呼び出し元オブジェクトへの参照です (通常はメソッドが属するオブジェクトですが、メソッドがセカンダリ オブジェクトのコンテキストから静的に呼び出される場合は別のオブジェクトになる可能性があります)。
クラスを作成するとき、(多くの場合) インスタンス変数とメソッド (別名関数) があります。$this はこれらのインスタンス変数にアクセスして、関数がそれらの変数を受け取り、必要なことを実行できるようにします。
meder の例の別のバージョン:
class Person {
protected $name; //can't be accessed from outside the class
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
// this line creates an instance of the class Person setting "Jack" as $name.
// __construct() gets executed when you declare it within the class.
$jack = new Person("Jack");
echo $jack->getName();
Output:
Jack
$this
呼び出し元オブジェクトへの参照です(通常はメソッドが属するオブジェクトですが、メソッドがセカンダリ オブジェクトのコンテキストから静的に呼び出される場合は、別のオブジェクトになる可能性があります)。
$this は特別な変数で、同じオブジェクトを参照します。自体。
実際には現在のクラスのインスタンスを参照します
上記のステートメントをクリアする例を次に示します
<?php
class Books {
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par){
$this->price = $par;
}
function getPrice(){
echo $this->price ."<br/>";
}
function setTitle($par){
$this->title = $par;
}
function getTitle(){
echo $this->title ." <br/>";
}
}
?>
mederが言ったように、それは現在のクラスのインスタンスを参照します。
PHP ドキュメントを参照してください。最初の例で説明します。