When would you use the $this keyword in PHP?

前端 未结 12 1743
长发绾君心
长发绾君心 2020-12-15 11:03

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

Al

12条回答
  •  悲&欢浪女
    2020-12-15 11:26

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

提交回复
热议问题