php-oo:为什么这段代码只打印第一个对象


php oo: why does this code prints only the first objects?

<?php
//firt class of eitay
class hello
    {
        //hello word.
        public $first = 'hello world';
        public function first_method()
        {
            $a = 1;
            $b = 2;
            $c = $a + $b;
            return $c;
            return $this->first;
        }
    }
    $momo = new hello();
    print $momo->first_method();

它只打印$c,因为函数在那之后返回。当您返回一个函数(在本例中为return $c)时,它将停止执行并返回到调用函数。

一个方法只返回一次并立即返回。多个返回语句是多余的,因为只执行第一个。

如果你想返回多个结果,你可以使用一个关联数组:

return array(
    "result" => $my_result,
    "time" => $end_time - $start_time
);

当第一个return退出函数并输出值为3$c时,应打印3

http://php.net/manual/en/function.return.php

如果从函数中调用,return语句将立即结束当前函数的执行,并将其参数返回为函数调用的值。return还将结束eval()语句或脚本文件。

如果从全局范围调用,则执行当前脚本文件已结束。如果包括或需要当前脚本文件,则控制权被传递回调用文件。此外,如果如果包含当前脚本文件,则给定的返回值将作为include调用的值返回。如果从调用return在主脚本文件中,然后脚本执行结束。如果当前脚本文件由auto_prepend_file或auto_append_file配置选项,然后该脚本文件的执行结束。

所以这是不可能发生的进行测试:http://ideone.com/HhzQa

正如其他人所说,php正在返回它看到的第一个返回

我还要问你为什么不把这个方法当作一个对象&更像是一个函数的封装。

如果你想在一个方法中创建多个值,只需用$this将它们分配给对象范围,那么只要该属性是公共的(默认情况下是公共的),你就可以从类外访问该属性,这里有一个例子:

<?php 
class hello{
    public $first = 'hello world';
    function first_method(){
        $this->a = 1;
        $this->b = 2;
        $this->c = $this->a + $this->b;
    }
    function add_more($key, $value){
        $this->$key += $value;
    }
}
$momo = new hello();
$momo->first_method();
echo $momo->first; //hello world
echo $momo->a; //1
echo $momo->b; //2
echo $momo->c; //3
//Alter the propery with a method
$momo->add_more('a', 5); //1+5=6
$momo->add_more('b', 53);//2+53=55
echo $momo->a;//6
echo $momo->b;//55
?>

传递数组不是oop。