Bu PHP değişken $ ne demek?

5 Cevap php

Ben değişkeni $this PHP her zaman görmek ve ne için kullanılır ne hiçbir fikrim yok. Ben şahsen hiç kullanmadım, ve arama motorları $ görmezden ve ben kelime "bu" için bir arama ile sonuna kadar.

Birisi bu PHP nasıl çalıştığını değişken $ bana söyleyebilir?

5 Cevap

Bu mevcut nesnenin bir başvuru var, bu en yaygın nesne yönelimli kod kullanılır.

Örnek:

<?php
class Person {
    public $name;

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

$jack = new Person('Jack');
echo $jack->name;

Bu yaratılan nesnenin bir özelliği olarak 'Jack' dizesi saklar.

Bu kendi içinde, aynı diğer birçok nesne yönelimli dillerden bir sınıfın bir örneğini başvuru yoludur.

Kimden PHP docs:

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

Eğer bir sınıf oluşturmak zaman (birçok durumda) örnek değişkenler ve yöntemleri (aka. fonksiyonlar) var. Lütfen fonksiyonları onlarla ne istersen ne yapmak gerekir bu değişkenleri almak ve yapmak, böylece $ bu bu örnek değişkenleri erişir.

Meder örneğinden başka bir versiyonu:

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

Php $this değişkeni hakkında bilgi edinmek için en iyi yolu nedir PHP sormaktır. Derleyici sormak, bize sormayın:

print gettype($this);            //object
print get_object_vars($this);    //Array
print is_array($this)            //false
print is_object($this)           //true
print_r($this);                  //dump of the objects inside it
print count($this);              //true
print get_class($this);          //YourProject\YourFile\YourClass
print isset($this);              //true
print get_parent_class($this)    //YourBundle\YourStuff\YourParentClass
print gettype($this->container)  //object

meder dediği gibi, mevcut sınıfın örneğini ifade.

PHP Docs bakın. Bu ilk örnek altında açıklanan oluyor.