许多召唤方法 - 通知

时间:2017-07-27 00:50:36

标签: 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 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);

通知:

  

1注意:未初始化的字符串偏移:1英寸   第25行/opt/lampp/htdocs/oop/test/test.php

     

注意:未初始化的字符串偏移量:0英寸   第22行/opt/lampp/htdocs/oop/test/test.php

     

注意:未初始化的字符串偏移量:0英寸   第22行/opt/lampp/htdocs/oop/test/test.php

     

注意:未初始化的字符串偏移量:1英寸   第25行/opt/lampp/htdocs/oop/test/test.php

     

注意:未初始化的字符串偏移量:0英寸   第22行/opt/lampp/htdocs/oop/test/test.php

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

在第一次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);