2016-10-02 23 views
1

我目前正在使用PHP并正在阅读PHP手册,但仍存在$ this的问题。

$ this this global or it is just another variable name to build objects on?

下面是一个例子:

public function using_a_function($variable1, $variable2, $variable3) 
{ 
    $params = array(
     'associative1' => $variable1, 
     'associative2' => $variable2, 
     'associative3' => $variable3 
    ); 
    $params['associative4'] = $this->get_function1($params); 
    return $this->get_function2($params); 
} 

如何将$这项工作的返回功能?我想我对这个函数的构建感到困惑。我知道建立一个名为key names => value的关联数组部分,但是$ this在这个例子中抛弃了我。

回答

2

它被称为Object范围,我们使用一个示例类。

Class Example 
{ 
    private $property; 
    public function A($foo) 
    { 
     $this->property = $foo; 
     // we are telling the method to look at the object scope not the method scope 
    } 
    public function B() 
    { 
     return self::property; // self:: is the same as $this 
    } 
} 

我们现在可以例如我们的对象和也是另一种方式来使用它:

$e = new Example; 
$e::A('some text'); 
// would do the same as 
$e->A('some other text'); 

这是访问对象的范围,因为方法不能访问其他方法范围的只是一种方法。

您还可以扩展一个类,并使用父::调用类扩展范围,例如:

Class Db extends PDO 
{ 
    public function __construct() 
    { 
     parent::__construct(.... 

这将访问PDO构造方法,而不是其自身的构造方法。

就你而言,该方法正在调用对象中的其他方法。可以使用$ this->或self ::

3

$this仅用于面向对象编程(OOP)并引用当前对象。

class SomeObject{ 
    public function returnThis(){ 
     return $this; 
    } 
} 

$object = new SomeObject(); 
var_dump($object === $object->returnThis()); // true 

这是用于对象内部的成员变量和方法。

class SomeOtherClass{ 
    private $variable; 
    public function publicMethod(){ 
     $this->variable; 
     $this->privateMethod(); 
    } 
    private function privateMethod(){ 
     // 
    } 
}