PHP stdClass vs“普通命名”类

时间:2016-06-11 18:27:16

标签: php object anonymous-class

在过去,我使用自己的课程来做很多事情。我知道,PHP本身提供了stdClasses。 所以我认为,将它们用于小对象会更有效率,因为我不需要创建数百个新类(“辅助类”)。

示例:

public function getStatus() {
    $status = new Status("1", "success");
    return $status
}

类:

class Status
{
    private $id;
    private $name;

    public function __construct($id, $name)
    {
        $this->id = $id;
        $this->name = $name;
    }

    public function getId()
    {
        return $this->id;
    }

    public function getName()
    {
        return $this->name;
    }

}

(正如你所看到的,我需要这样的课程的唯一原因是“返回”数据)

因此,当我每次编写这样的代码时,就像我说的那样,我必须创建许多类以供少量使用。

在像我这样的情况下使用stdClass对象会不会更好?这个想法的缺点是什么?

1 个答案:

答案 0 :(得分:0)

对我来说最好使用辅助器/类,如ArrayObject,Data,DataAccess等。 这个助手/类的思想是快速存储和访问数据。

我从不使用stdClass对象。即使我使用像json_decode这样的函数,我把第二个参数设为true来获取数组数组而不是stdClasses数组。

希望你了解我。抱歉英语不好:)

例如:

/**
 * @package   com_zoo
 * @author    YOOtheme http://www.yootheme.com
 * @copyright Copyright (C) YOOtheme GmbH
 * @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
 */

/**
 * Class for reading and writing in various formats
 *
 * @package Framework.Classes
 */
class AppData extends ArrayObject
{

    /**
     * Class constructor
     *
     * @param array $data The data array
     */
    public function __construct($data = array())
    {
        parent::__construct($data ? $data : array());
    }

    /**
     * Checks if the given key is present
     *
     * @param string $name The key to check
     *
     * @return boolean If the key was found
     *
     * @since 1.0.0
     */
    public function has($name)
    {
        return $this->offsetExists($name);
    }

    /**
     * Get a value from the data given its key
     *
     * @param string $key     The key used to fetch the data
     * @param mixed  $default The default value
     *
     * @return mixed The fetched value
     *
     * @since 1.0.0
     */
    public function get($key, $default = null)
    {

        if ($this->offsetExists($key)) {
            return $this->offsetGet($key);
        }

        return $default;
    }

    /**
     * Set a value in the data
     *
     * @param string $name  The key used to set the value
     * @param mixed  $value The value to set
     *
     * @return AppData The AppData object itself to allow chaining
     *
     * @since 1.0.0
     */
    public function set($name, $value)
    {
        $this->offsetSet($name, $value);

        return $this;
    }

    /**
     * Remove a value from the data
     *
     * @param string $name The key of the data to remove
     *
     * @return AppData The AppData object itself to allow chaining
     *
     * @since 1.0.0
     */
    public function remove($name)
    {
        $this->offsetUnset($name);

        return $this;
    }

    /**
     * Magic method to allow for correct isset() calls
     *
     * @param string $name The key to search for
     *
     * @return boolean If the value was found
     *
     * @since 1.0.0
     */
    public function __isset($name)
    {
        return $this->offsetExists($name);
    }

    /**
     * Magic method to get values as object properties
     *
     * @param string $name The key of the data to fetch
     *
     * @return mixed The value for the given key
     *
     * @since 1.0.0
     */
    public function __get($name)
    {
        return $this->offsetGet($name);
    }

    /**
     * Magic method to set values through object properties
     *
     * @param string $name  The key of the data to set
     * @param mixed  $value The value to set
     *
     * @since 1.0.0
     */
    public function __set($name, $value)
    {
        $this->offsetSet($name, $value);
    }

    /**
     * Magic method to unset values using unset()
     *
     * @param string $name The key of the data to set
     *
     * @since 1.0.0
     */
    public function __unset($name)
    {
        $this->offsetUnset($name);
    }

    /**
     * Magic method to convert the data to a string
     *
     * Returns a serialized version of the data contained in
     * the data object using serialize()
     *
     * @return string A serialized version of the data
     *
     * @since 1.0.0
     */
    public function __toString()
    {
        return empty($this) ? '' : $this->_write($this->getArrayCopy());
    }

    /**
     * Utility Method to serialize the given data
     *
     * @param mixed $data The data to serialize
     *
     * @return string The serialized data
     *
     * @since 1.0.0
     */
    protected function _write($data)
    {
        return serialize($data);
    }

    /**
     * Find a key in the data recursively
     *
     * This method finds the given key, searching also in any array or
     * object that's nested under the current data object.
     *
     * Example:
     * <code>
     * $data->find('parentkey.subkey');
     * </code>
     *
     * @param string $key       The key to search for. Can be composed using $separator as the key/subkey separator
     * @param mixed  $default   The default value
     * @param string $separator The separator to use when searching for subkeys. Default is '.'
     *
     * @return mixed The searched value
     *
     * @since 1.0.0
     */
    public function find($key, $default = null, $separator = '.')
    {

        $key   = (string)$key;
        $value = $this->get($key);

        // check if key exists in array
        if ($value !== null) {
            return $value;
        }

        // explode search key and init search data
        $parts = explode($separator, $key);
        $data  = $this;

        foreach ($parts as $part) {

            // handle ArrayObject and Array
            if (($data instanceof ArrayObject || is_array($data)) && isset($data[$part])) {

                if ($data[$part] === null) {
                    return $default;
                }

                $data =& $data[$part];
                continue;
            }

            // handle object
            if (is_object($data) && isset($data->$part)) {

                if ($data->$part === null) {
                    return $default;
                }

                $data =& $data->$part;
                continue;
            }

            return $default;
        }

        // return existing value
        return $data;
    }

    /**
     * Find a value also in nested arrays/objects
     *
     * @param mixed $needle The value to search for
     *
     * @return string The key of that value
     *
     * @since 1.0.0
     */
    public function searchRecursive($needle)
    {
        $aIt = new RecursiveArrayIterator($this);
        $it  = new RecursiveIteratorIterator($aIt);

        while ($it->valid()) {
            if ($it->current() == $needle) {
                return $aIt->key();
            }

            $it->next();
        }

        return false;
    }

    /**
     * Return flattened array copy. Keys are <b>NOT</b> preserved.
     *
     * @return array The flattened array copy
     *
     * @since 1.0.0
     */
    public function flattenRecursive()
    {
        $flat = array();
        foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($this)) as $value) {
            $flat[] = $value;
        }

        return $flat;
    }
}



$array = array(
    'simple' => 'very simple array',
    'big'    => array(
        'bigbig' => array(
            'bigbigbig' => 'third level'
        )
    )
);
$data = new AppData($array);

echo $data->get('simple');                // very simple array
echo $data->find('big.bigbig.bigbigbig'); // third level
echo $data->get('not_found', 'novalue');  // novalue
相关问题