有如下4个代码示例,你认为他们创建对象,并且获得成员变量的速度排序是怎样的?
1:将成员变量设置为public,通过赋值操作给成员变量赋值,直接获取变量
复制代码 代码如下:
<?php
class Foo {
public $id;
}
$data = new Foo;
$data->id = 10;
echo $data->id;
?>
复制代码 代码如下:
<?php
class Foo2 {
public $id;
public function __construct($id) {
$this->id = $id;
}
}
$data = new Foo2(10);
echo $data->id;
?>
复制代码 代码如下:
<?php
class Foo3 {
protected $id;
public function __construct($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
$data = new Foo3(10);
echo $data->getId();
?>
public function __get($key) {
return $this->id;
}
}
$data = new Foo4(10);
echo $data->id;
?>
按执行速度快慢排序: 1243
咱们先看其opcode:
1:
复制代码 代码如下:
1 ZEND_FETCH_CLASS 4 :4 'Foo'
2 NEW $5 :4
3 DO_FCALL_BY_NAME 0
4 ASSIGN !0, $5
5 ZEND_ASSIGN_OBJ !0, 'id'
6 ZEND_OP_DATA 10
7 FETCH_OBJ_R $9 !0, 'id'
8 ECHO $9
复制代码 代码如下:
1 ZEND_FETCH_CLASS 4 :10 'Foo2'
2 NEW $11 :10
3 SEND_VAL 10
4 DO_FCALL_BY_NAME 1
5 ASSIGN !1, $11
6 FETCH_OBJ_R $14 !1, 'id'
7 ECHO $14
复制代码 代码如下:
1 ZEND_FETCH_CLASS 4 :15 'Foo3'
2 NEW $16 :15
3 SEND_VAL 10
4 DO_FCALL_BY_NAME 1
5 ASSIGN !2, $16
6 ZEND_INIT_METHOD_CALL !2, 'getId'
7 DO_FCALL_BY_NAME 0 $20
8 ECHO $20
复制代码 代码如下:
1 ZEND_FETCH_CLASS 4 :21 'Foo4'
2 NEW $22 :21
3 END_VAL 10
4 DO_FCALL_BY_NAME 1
5 ASSIGN !3, $22
6 FETCH_OBJ_R $25 !3, 'id'
7 ECHO $25
新闻热点
疑难解答