17

I have been using arrays to store related fields during a long time. If I wanted to have related user fields, I used:

$user = array(
   'id' => 27
   'name' => 'Pepe'
);

But lately, I've been working a lot with objects, and I like it more to use $user->id instead of $user['id'].

My question: To achieve an object oriented style, you may use stdClass:

$user = new stdClass();
$user->id = 27;
$user->name = 'Pepe';

or casting from an array

$user = (object) array(
  'id' => 27
, 'name' => 'Pepe'
);

Is one of them better than the other, in order of performance and style, or can you use whatever you want indistinctly?

Thanks!

Update: I agree with all the comments, this is not OOP at all, is just about having related data grouped into a structure. My $user example is not the best, because it's a typical example of using classes with method, properties, blablabla... I asked because I have a lot of config structures, such us "initTable", and I want something like:

$table => page => init => 1
               => end  => 25
          sort => field => name
               => order => asc

and so on, and I want to know what is better to get init page:

$table->page->init **OR** $table['page']['init']
4

3 回答 3

10

基于小测试(http://phpfiddle.org/lite/code/cz0-hyf),我可以说使用“new stdClass()”比其他选项慢大约 3 倍。

这很奇怪,但是与 stdClass 相比,强制转换数组非常有效。

但是这个测试只测量执行时间。它不计量内存。

PS 我只使用 phpFiddle 来共享代码。测试是在我的本地 PC 上完成的。

于 2013-09-05T15:56:40.630 回答
8

尝试调查这个问题,这里每个测试做 1.000.000 次:

$start = microtime(true);
for ($i=0;$i<1000000;$i++) {
    $user = new stdClass();
    $user->id = 27;
    $user->name = 'Pepe';
}
$end = microtime(true);
echo $end - $start;

echo '<br><br>';

$start = microtime(true);
for ($i=0;$i<1000000;$i++) {
    $user = (object) array(
        'id' => 27, 
        'name' => 'Pepe'
    );
}
$end = microtime(true);
echo $end - $start;

报告

0.75109791755676
0.51117610931396

所以 -显然在这种特殊情况下- 从数组转换是最快的方法。击败stdClass许多百分比。但我不会指望它作为普遍的普遍规则或法律。

于 2013-09-05T15:54:44.823 回答
4

我不认为将数组移动到标准对象会有所作为。除了你不能再使用大部分array_*功能了。
我看不到使用动态对象而不是索引数组的任何优势。

在这种情况下,我将为您需要的每个元素和属性创建一个类。

class User
{
    protected $id;
    protected $name;

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

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

    public function setName($name)
    {
        $this->name = $name;
    }
}

通过这样的设计,您可以确切地知道您拥有什么样的参数。

$user  = new User(21, 'Foo');
echo $user->getName(); // Foo

$blank = new User(22);
echo $blank->getName(); // NULL

没有错误,不再检查。
使用arrayorstdClass你会有类似的东西

$user = array('id' => 21, 'name' => 'Foo');
echo $user['name']; // Foo

$blank = array('id' => 22);
echo $blank['name']; // NOTICE: Undefined offset
echo isset($blank['name']) ? $blank['name'] : null; // NULL

对于这种行为,拥有一个您知道界面的实体对象更易于维护和扭曲。

于 2013-09-05T15:56:06.180 回答