开发者

When would you use the $this keyword in PHP?

When would you use the $this keyword in PHP? From what I understand $this refers to the object created without knowing the objects name.

Also the keyword $this can only be used within a method?

An example would be great to show when you can use $th开发者_如何学Cis.


A class may contain its own constants, variables (called "properties"), and functions (called "methods").

<?php
class SimpleClass
{
    // property declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
        echo $this->var;
    }
}
?>

Some examples of the $this pseudo-variable:

<?php
class A
{
    function foo()
    {
        if (isset($this)) {
            echo '$this is defined (';
            echo get_class($this);
            echo ")\n";
        } else {
            echo "\$this is not defined.\n";
        }
    }
}

class B
{
    function bar()
    {
        // Note: the next line will issue a warning if E_STRICT is enabled.
        A::foo();
    }
}

$a = new A();
$a->foo();

// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
$b = new B();
$b->bar();

// Note: the next line will issue a warning if E_STRICT is enabled.
B::bar();
?>

The above example will output:

  • $this is defined (A)
  • $this is not defined.
  • $this is defined (B)
  • $this is not defined.


The most common use case is within Object Oriented Programming, while defining or working within a class. For example:

class Horse {
    var $running = false;

    function run() {
        $this->running = true;
    }
}

As you can see, within the run function, we can use the $this variable to refer to the instance of the Horse class that we are "in". So the other thing to keep in mind is that if you create 2 Horse classes, the $this variable inside of each one will refer to that specific instance of the Horse class, not to them both.


You would only use $this if you are doing Object Oriented programming in PHP. Meaning if you are creating classes. Here is an example:

class Item {
  protected $name, $price, $qty, $total;

  public function __construct($iName, $iPrice, $iQty) {
    $this->name = $iName;
    $this->price = $iPrice;
    $this->qty = $iQty;
    $this->calculate();
  }

}


$this is used to make a reference to the current instance of an object. So you can do things like:

class MyClass {
    private $name;

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

    //vs
    public function setName($pName) {
        $name = $pName;
    }
}

Also another cool use is that you can chain methods:

class MyClass2 {
    private $firstName;
    private $lastName;

    public function setFirstName($name) {
        $this->firstName = $name;
        return $this;
    }

    public function setLastName($name) {
        $this->lastName = $name;
        return $this;
    }

    public function sayHello() {
        print "Hello {$this->firstName} {$this->lastName}";
    }
}

//And now you can do:
$newInstance = new MyClass2;
$newInstance->setFirstName("John")->setLastName("Doe")->sayHello();


It's used in Object-oriented Programming (OOP):

<?php
class Example
{  
    public function foo()
    {
        //code
    }

    public function bar()
    {
        $this->foo();
    }
}

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).


Used for when you want to work with local variables.

You can also read more about it from here.

function bark() {
    print "{$this->Name} says Woof!\n";
}


One time I know I end up using the this equivalent in other languages is to implement a 'Fluent' interface; each class method which would otherwise return void instead returns this, so that method calls can be easily chained together.

public function DoThis(){
    //Do stuff here...
    return $this;
}
public function DoThat(){
   //do other stuff here...
   return $this;
}

The above could be called like so:

myObject->DoThis()->DoThat();

Which can be useful for some things.


$this is used when you have created a new instance of an object.

For example, imagine this :

class Test {
    private $_hello = "hello";

    public function getHello () {
        echo $this->_hello; // note that I removed the $ from _hello !
    }

    public function setHello ($hello) {
        $this->_hello = $hello;
    }
}

In order to access to the method getHello, I have to create a new instance of the class Test, like this :

$obj = new Test ();
// Then, I can access to the getHello method :
echo $obj->getHello ();
// will output "hello"

$obj->setHello("lala");
echo $obj->getHello ();
// will output "lala"    

In fact, $this is used inside the class, when instancied. It is refered as a scope.

Inside your class you use $this (for accessing *$_hello* for example) but outside the class, $this does NOT refer to the elements inside your class (like *$_hello*), it's $obj that does.

Now, the main difference between $obj and $this is since $obj access your class from the outside, some restrictions happens : if you define something private or protected in your class, like my variable *$_hello*, $obj CAN'T access it (it's private!) but $this can, becase $this leave inside the class.


no i think ur idea is wrong.. $this is used when refers to a object of the same class.. like this

think we have a variable value $var and in THAT instance of that object should be set to 5

$this->var=5;


The use $this is to reference methods or instance variables belonging to the current object

$this->name = $name or $this->callSomeMethod()

that is going to use the variable or method implemented in the current object subclassed or not.

If you would like to specifically call an implementation of of the parent class you would do something like

parent::callSomeMethod()


Whenever you want to use a variable that is outside of the function but inside the same class, you use $this. $this refers to the current php class that the property or function you are going to access resides in. It is a core php concept.


<?php
  class identity {
    public $name;
    public $age;
    public function display() {
      return $this->name . 'is'. $this->age . 'years old';
    }
  }
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜