Php 许多调用方法-注意
我尝试设置许多相同的方法。该参数取决于数组元素。如果案例:1-显示“1”号,如果案例:2-显示“2”号。我提供代码:Php 许多调用方法-注意,php,Php,我尝试设置许多相同的方法。该参数取决于数组元素。如果案例:1-显示“1”号,如果案例:2-显示“2”号。我提供代码: <?php error_reporting(E_ALL); ini_set('display_errors', 1); class Test { protected $target = array('1' ,'2'); private $message; public function setTa
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
class Test {
protected $target = array('1' ,'2');
private $message;
public function setTarget($target) {
return $this->target = $target;
}
public function getTarget() {
return $this;
}
public function getMessage() {
return $this->message;
}
public function set($target) {
switch($target) {
case '1':
$this->message = $this->setTarget($this->target[0]);
break;
case '2':
$this->message = $this->setTarget($this->target[1]);
break;
}
return
$this->message; $this->target;
}
}
$foo = new Test;
echo $foo->set(1);
echo $foo->set(2);
echo $foo->set(1);
echo $foo->set(1);
echo $foo->set(2);
echo $foo->set(1);
在第一次set
方法调用中,setTarget
将目标列表的值更改为$this->target[0]
将目标列表与当前目标分开。在下面的示例中,我将$message
转换为当前目标,可用目标列表位于$targets
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
class Test {
protected $targets = array('1' ,'2');
private $currentTarget;
public function setTarget($target) {
// set the current target, do not override $this->targets
return $this->currentTarget = $target;
}
public function getTarget() {
// why are you returning $this here
// imo, should be $this->currentTarget;
return $this;
}
public function getMessage() {
return $this->message;
}
public function set($target) {
switch($target) {
case '1':
$this->currentTarget = $this->setTarget($this->targets[0]);
break;
case '2':
$this->currentTarget = $this->setTarget($this->targets[1]);
break;
}
return
$this->currentTarget;
}
}
$foo = new Test;
echo $foo->set(1);
echo $foo->set(2);
echo $foo->set(1);
echo $foo->set(1);
echo $foo->set(2);
echo $foo->set(1);
只要调用setTarget
,您就会用字符串覆盖$target
数组。另外,setTarget
不会返回任何内容,因此当您第一次回显$foo->set(1)时,它不会为$this->message
分配任何值;受保护的目标值是目标[0],而不是您的ini阵列您有什么建议?如何修理?