Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/248.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php中的方法链接行为奇怪_Php - Fatal编程技术网

php中的方法链接行为奇怪

php中的方法链接行为奇怪,php,Php,我用php编写了一个函数,以了解方法链接在php中的工作原理。但是它没有显示任何输出 我的代码是: class sample { function something($array) { $samples = array(); foreach($array as $key=>$value) { $this->$key = $value; return $key; } } } $hot = new sample(); $h

我用php编写了一个函数,以了解方法链接在php中的工作原理。但是它没有显示任何输出

我的代码是:

class sample {

function something($array) {

    $samples = array();
    foreach($array as $key=>$value) {

        $this->$key = $value;
        return $key;
    }
}
}

$hot = new sample();
$hot->something(array('maths'=>'12','science'=>'10'));

echo $hot->something()->maths;
?>
当我运行这段代码时,我没有得到任何输出。我得到了类似警告:sample::something缺少参数1,在第22行的/web/com/13987442563085/main.php中调用,在第10行的/web/com/13987442563085/main.php中定义警告:为foreach提供的参数无效

这里我的预期输出是1

希望你们能帮我找到正确的输出。任何帮助都将不胜感激。

试试这个

<?php
class sample {



  function something($array) {

$samples = array();
foreach($array as $key=>$value) {

 $this->$key = $value;
 return $value;
}
 }
}

$hot = new sample();
echo $hot->something(array('number'=>'1','subject'=>'maths'));
?>

你的代码从前到后毫无意义

您正在调用$hot->一些没有任何参数的东西,然后您想知道是否有错误消息确切地告诉您这一点

在foreach循环中使用return,就像这样,在第一次循环迭代中打破了它和整个方法

你不能在这里“链接”任何东西,除了你想要的,实际上不是“方法链接”,因为你没有在这里连续调用多个方法,因为你的方法没有返回值。如果您希望能够“根据”方法调用的结果或调用另一个方法访问对象的属性,则必须返回该对象:

class Sample {
  function something($array) {
    foreach($array as $key=>$value) {
        $this->$key = $value;
    }
    return $this;
  }
}

$hot = new Sample();
echo $hot->something(array('maths'=>'12','science'=>'10'))->maths;

这将输出12。它仍然没有多大意义。

首先,您将数组传递给未定义的构造函数。它的行为异常,因为代码非常奇怪。对不起……这是我的错误……方法链接?你们班上只有一种方法。您至少需要两种方法来链接;number和subject不是$this->number和$this->subject中未声明的变量吗?我对$this->$key=$value有疑问;你能帮我理解一下吗?请参考问题部分的评论好的..谢谢,这是我想要的输出..我只是尝试通过方法链接过程来实现,而您通过方法链接正确地实现了..谢谢..@asprin:类成员不必在PHP中显式声明,使用$this->foo='bar'将动态创建具有公共可见性的foo,前提是之前没有明确声明。谢谢。但是你不是说$this->foo='bar'将创建foo而不是$this->foo='bar'将创建bar吗?i、 当然,e$foo等于barAh。编辑了我之前的评论,以免进一步混淆任何人。