$this在php代码中单独运行
我被$this搞糊涂了。我知道$this->somevaribale用于引用全局值……但我看到过这样的代码$this在php代码中单独运行,php,Php,我被$this搞糊涂了。我知道$this->somevaribale用于引用全局值……但我看到过这样的代码 class ClassName { private $array; //set up a variable to store our array /* * You can set your own array or use the default one * it will set the $this->array variable to whatever array is
class ClassName
{
private $array; //set up a variable to store our array
/*
* You can set your own array or use the default one
* it will set the $this->array variable to whatever array is given in the construct
* How the array works like a database; array('column_name' => 'column_data')
*/
function __construct($array = array('fruit' => 'apple', 'vegetable' => 'cucumber')) {
$this->array = $array;
}
/*
* Loops through the array and sets new variables within the class
* it returns $this so that you may chain the method.
*/
public function execute() {
foreach($this->array AS $key => $value) {
$this->$key = $value; //we create a variable within the class
}
return $this; //we return $this so that we can chain our method....
}
}
这里单独调用$this…我真的对它感到困惑..当我删除$this并替换为$this->array时,我得到了错误
所以我的问题是单独调用$this有什么用,它代表了什么
Thanx提供帮助。$这是PHP对象的参考。您可以在PHP手册中了解有关对象和$this如何工作的更多信息,并对您使用的术语进行一些更正: $这是对当前对象的引用,而不是全局值 你在这里什么都没打电话;调用函数时,只需使用$this,它也是一个保存对象的变量 因此,return$返回当前对象作为方法的返回值。这样做通常只是为了简化流畅的界面,在这种风格中,您可以编写如下代码:
$foo->bar()->baz()
因为bar返回一个对象$this object,所以您可以随后调用它的方法baz。类是对象的蓝图,反之亦然,而对象是类的实例。在类中使用$this时,它指的是它自己
$hi = new ClassName();
$hi->execute()->method()->chaining()->is_like_this();
$hi引用一个ClassName对象,函数execute返回对象本身
$ha = $hi->execute();
// $ha refers to a ClassName object.
如果一个人通常调用该对象的许多方法,那么方法链接fluent接口可以使他整理代码:
$hi->doSome();
$hi->doAnotherThing();
$hi->thirdMethodCall();
$hi->etcetera();
将成为
$hi->doSome()
->doAnotherThing()
->thirdMethodCall()
->etcetera();
$this指的是包含$array的对象。请参阅Interfaces@Wold包含$array的对象意味着???..如果我像$wold=new classname那样调用,..那么$this指的是$wold???@honeysingh No。您只能在类或函数的上下文中返回“$this”并引用“$this”。如果您正在声明$wold=new classname$现在它只在类中与$wold关联。因此$this====$wold在类中??因此$this在类中指的是类的对象?/ie$hi?事实上,$this指的是调用方法的对象。因此这里$foo->bar===$this在类中??在bar中,$this===$foo.所以当我像$name=newclassname,$name->execute这样运行时,这里是$name->execute===$foo对吗?什么?不在execute方法内部,$this指的是$name。如果您返回$this,那么$name->execute本质上返回$name。那么在类的execute方法$this===$nameobject中,对吗?