PHP中返回方法的最佳

PHP中返回方法的最佳

本文介绍了PHP中返回方法的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么是这种情况的最佳实践,在PHP中:

Which and why are the best practices for this case, in PHP:

class Main {
    public function getSomeBean() {
        ...
        return array(
            'value1' => $value1,
            'value2' => $value2
        );
    }
}

class SomeBean() {
    $value1;
    $value2;
}
class Main {
    public function getSomeBean() {
        $someBean = new SomeBean();
        ...
        return $someBean;
    }
}

在java中是一个最佳实践,总是使用一个bean类。但是在PHP中我总是看到返回数组,但是在Netbeans中很难知道数组的关键是什么,只读文档,用一个类更容易,但另一方面给了更多的工作。
所以...最好的方法是什么?

In java is a best practice use always a bean class. But in PHP i always see return array, but in Netbeans is hard to know what is the keys of array, only reading the docs, with a class is more easy, but on the other hand, gives more work.So... what is the best way?

推荐答案

取决于你回来的内容。如果有一个容器类(很像C结构体),你可以去找它。如果您返回相同类型的数据,那么您应该去使用数组。

Depends on what you are returning. If it makes sense to have a container class (pretty much like C structs) you can go for it. If you are returning the same type of data you should go for arrays instead.

但是创建一个只是旧的特定类型的返回值的类没有意义。您可以使用正确的构造函数和正确的方法创建一个完整的类,或者您只需使用 stdClass

But creating a class just to old a specific type of return values doesn't make sense. Either you create a complete class with a proper constructor and proper methods or you just use stdClass.

使用 stdClass 数组作为容器并不重要。那里没有对错。例如PDO提供了两者,因为它取决于你和你的风格。

At that point using stdClass or array as a container doesn't really matter much. There's no right or wrong there. PDO for example provides both, because it's up to you and your style.

这篇关于PHP中返回方法的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 00:49