我目前正在使用PHP,正在阅读PHP手册,但仍然有一个问题$this。
$this是全局的还是只是另一个变量名来构建对象?
下面是一个例子:
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);
}
$this如何用于返回函数?我想我对这个函数是如何构建的感到困惑。我理解构建关联数组部分的名称是一个值key names => value
,但$这让我在这个例子。
$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(){
//
}
}
它被称为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');
这只是访问Object作用域的一种方式,因为方法不能访问其他方法作用域。
您还可以扩展类并使用parent::来调用类的扩展作用域,例如:
Class Db extends PDO
{
public function __construct()
{
parent::__construct(....
它将访问PDO构造方法而不是它自己的构造方法。
在你的例子中,方法正在调用对象中的其他方法。可以使用$this->或self::