What does $this actually mean> Codeigniter

2019-01-17 22:39发布

问题:

Silly question I know,

From all the tutorials they do not explain why they use $this.

Is $this like an object from a base class in Codeigniter?

Any explanation would be welcomed! :)

Thanks

回答1:

To actually answer your question, $this actually represents the singleton Codeigniter instance (which is actually the controller object).

For example when you load libraries/models, you're attaching them to this instance so you can reference them as a property of this instance.

Another way to get this instance in codeigniter is the get_instance() function that you use when building portable libraries.



回答2:

$this in PHP is the current object. In a class definition, you use $this to work with the current object. Take this class as an example:

class Hello {
  public $data = 'hello';
  function hi() {
    $this->data = 'hi';
  }
}

You can instantiate this class multiple times, but $data will only be changed to hi in those objects where you called the function:

$one = new Hello;
$two = new Hello;
$two->hi();

echo $one->data, "\n", $two->data;


回答3:

$this isn't something from CodeIgniter, but from PHP. $this refers to the current object.

Whenever you create an instance like this:

$something = new SomeClass();

Then $this refers to the instance that is created from SomeClass, in this case $something. Whenever you are in the class itself, you can use $this to refer to this instance. So:

class SomeClass {

  public $stuff = 'Some stuff';

  public function doStuff()
  {
    $this->stuff;
  }

}


回答4:

In terms of codeigniter:
You'll notice that each controller in codeigniter extends the base controller class. Using $this in a controller gives you access to everything which is defined in your controller, as well as what's inherited from the base controller.

Most of the use you'll get out of $this involves calling methods which the base class has loaded for you - $this->load, $this->uri, etc.

If I remember correctly, PHP code in a view is run in the context of the controller, so you'll have access to the controller object with $this from there as well.



回答5:

I just read a great post about $this and classes in general: http://query7.com/using-this-in-php

In PHP, the keyword “$this” is used as a self reference of a class and you can use it for calling and using these properties and methods as shown in the example bellow.



回答6:

It is the way to reference an instance of a class from within itself, the same as many other object oriented languages. From the PHP docs: The pseudo-variable $this is available when a method is called from within an object context. ... $this is mainly used to refer properties of a class