how to create a php class which can be casted to boolean (be truthy or falsy)

前端 未结 6 1006
闹比i
闹比i 2021-01-17 16:11

I am creating a collection class and would like it to be drop-in-replacement for arrays, which I use currently.

How to create a class which could be casted

6条回答
  •  旧时难觅i
    2021-01-17 16:38

    If you don't want to implement your own method you could hack your way into __toString, like this:

    class foo
    {
        public function __toString()
        {
            return strval(false);
        }
    }
    
    $foo = new foo();
    
    if (strval($foo) == false) // non-strict comparison
    {
       echo '$foo is falsy';
    }
    
    echo (bool) strval($foo); // false
    

提交回复
热议问题