我正在尝试理解面向对象的PHP编程,并编写了一个小类来学习。我很难理解为什么它没有按照我想要的方式工作。我在类方法中有两个变量hello()
$result
和$test
。我正在尝试访问存储在这两个变量中的数据并将其打印到屏幕上。我知道我可以在方法内部调用回声,但我试图让它在方法之外回显。
我打印到屏幕上的是88
它没有打印出第二个变量$test
.我试图理解为什么会这样。我的缺乏理解可能表现在代码中。
<?php
class simpleClass{
public function hello($result,$test) {
$result = 4+4;
$test = 10+5;
return $result;
return $test;
}
}
$a = new simpleClass;
echo $a->hello();
echo $a->hello($result, $test);
?>
您可以返回list
或array
public function hello($result,$test) {
$result = 4+4;
$test = 10+5;
return array($result, $test);
}
使用参数引用:
class simpleClass{
public function hello(&$result, &$test) {
$result = 4+4;
$test = 10+5;
}
}
$a = new simpleClass;
$result=''; $test='';
$a->hello($result, $test);
echo $result;
echo '<br>';
echo $test;
8 15
澄清一下,当您将&
添加到函数参数时,该参数的值 - 如果您在函数中更改或操作它 - 将处理回传递的原始变量。因此,您甚至不必返回结果,例如将其打包到array
或stdObject
中,然后解压缩。但是您仍然可以从函数中返回一些内容,例如
$ok = $a->hello($result, $test);
例如,作为指示计算是否正确的标志。
由于return
的工作方式,您不能在同一函数中有多个return
语句。当遇到return
语句时,函数将停止执行,然后传递回调用方。函数的其余部分永远不会运行。
复杂的答案是使用模型。
class simpleResultTestModel {
public $result;
public $test;
public function __construct($result,$test) {
$this->result = $result;
$this->test = $test;
}
}
class simpleClass {
public function hello($result=4, $test=10) {
$result = $result+4;
$test = $test+5;
return new simpleResultTestModel($result, $test);
}
}
这样,您就知道simpleClass->hello()
将始终返回simpleResultTestModel
的实例。
另外,我更新了您的hello方法定义。您有两个参数,但实际上并不应用它们;我冒昧地设置了默认值,然后在计算中使用了它们。
用法:
$a = new simpleClass();
$first = $a->hello();
echo $first->result;
echo $first->test;
$second = $a->hello($first->result,$first->test);
echo $second->result;
echo $second->test;
我会尽量避免通过引用传递(尤其是在类定义中),除非您有正当理由这样做。创建类实例时(即"粘性值",如果您愿意),这是一种不好的做法。