duanfoumi5620 2010-06-16 10:36
浏览 11
已采纳

对对象强制执行empty()测试的结果

Simple class for example:

class Foo
{
    protected $_bar;

    public function setBar( $value ) {

        $this->_bar = $value;

    }

}

And here is the question:

$obj = new Foo();

  var_dump( empty( $obj ) );  // true

$obj->setBar( 'foobar' );

  var_dump( empty( $obj ) );  // false

Is it possible to change class's behaviour with testing it with empty() function so it will returns true when object is not filled with data ?

I know about magic function __isset( $name ) but it is called only when we test specific field like:

empty( $obj->someField );

but not when test whole object.

  • 写回答

3条回答 默认 最新

  • doukuang1950 2010-06-16 10:59
    关注

    It kind of is possible. The opcode calls i_zend_is_true:

        if (!isset || !i_zend_is_true(*value)) {
            ZVAL_BOOL(&EX_T(opline->result.var).tmp_var, 1);
        } else {
            ZVAL_BOOL(&EX_T(opline->result.var).tmp_var, 0);
        }
    

    which has this definition for objects (as of trunk):

        case IS_OBJECT:
            if(IS_ZEND_STD_OBJECT(*op)) {
                TSRMLS_FETCH();
    
                if (Z_OBJ_HT_P(op)->cast_object) {
                    zval tmp;
                    if (Z_OBJ_HT_P(op)->cast_object(op, &tmp, IS_BOOL TSRMLS_CC) == SUCCESS) {
                        result = Z_LVAL(tmp);
                        break;
                    }
                } else if (Z_OBJ_HT_P(op)->get) {
                    zval *tmp = Z_OBJ_HT_P(op)->get(op TSRMLS_CC);
                    if(Z_TYPE_P(tmp) != IS_OBJECT) {
                        /* for safety - avoid loop */
                        convert_to_boolean(tmp);
                        result = Z_LVAL_P(tmp);
                        zval_ptr_dtor(&tmp);
                        break;
                    }
                }
            }
            result = 1;
            break;
    

    So if a cast to bool results in the value false (or if thee object is a proxy object and proxied value converts to false), empty will return true. However, to take advantage of this, you have to write a custom object in a PHP extension.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算