简体   繁体   English

是什么导致php值是true和false?

[英]What could cause php value to be true and false?

I have a class with this function: 我有一个带有此功能的课程:

public static function getSingleton($modelClass='', array $arguments=array())
{
    $registryKey = '_singleton/'.$modelClass;
    if (!isset(self::$_registry[$registryKey])) {
        if (isset(self::$_registry[$registryKey])) {
            throw new Exception('Mage registry key "'.$registryKey.'" already exists');
        }
        self::$_registry[$registryKey] = self::getModel($modelClass, $arguments);
    }
    return self::$_registry[$registryKey];
}

The exception is being thrown. 引发异常。 HOW can the exception be thrown? 如何抛出异常? I can't think of any way that isset() and !isset() could both return true - yet they are! 我想不出isset()和!isset()都可以返回true的任何方式-但它们确实是! How could this happen? 这怎么可能呢? I am using APC, could that have anything to do with it? 我正在使用APC,这和它有什么关系吗? How would I even debug this? 我什至会调试呢?

Isset tests if the variable or index has been initialized or not and does not always use booleans. Isset测试变量或索引是否已初始化,并且不总是使用布尔值。 The value could just as well be null and the proper way of testing this (since PHP is loosely coupled) would be: 该值也可以为null,并且测试此值的正确方法(由于PHP是松散耦合的)将是:

if (isset(self::$_registry[$key]) === true)

Or better yet; 或者更好;

if (array_key_exists($key, self::$_registry))

I always suggest using array_key_exists instead of isset since the first one is much more reliable for true/false conditions. 我总是建议使用array_key_exists而不是isset,因为第一个对于true / false条件更加可靠。

Edit: Also, like the comments stated - your variable is $registryKey and not $key . 编辑:另外,就像陈述的注释一样-您的变量是$registryKey而不是$key

It is possible that the object has the magic method __isset() , which may cause some weird behaviours if coded poorly. 该对象可能具有魔术方法 __isset() ,如果编码不正确,则可能会导致一些奇怪的行为。

Also, it is possible that $registry isn't a simple array but an object which implements the ArrayAccess interface. 同样, $registry可能不是一个简单的数组,而是一个实现ArrayAccess接口的对象。 Then you must look for the __isset() magic method if present, and the method OffsetExists more precisely. 然后,您必须寻找__isset()魔术方法(如果存在),并且方法OffsetExists更精确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM