SplObjectStorage :: contains和SplObjectStorage :: offsetExists有什么区别?

Tiv*_*vie 12 php spl php-internals splobjectstorage

PHP文档不是很明确,只说明:

SplObjectStorage :: offsetExists 检查存储中是否存在对象.(PHP> = 5.3.0)

SplObjectStorage :: contains 检查存储是否包含提供的对象.(PHP> = 5.1.0)

这对我来说几乎是一回事.

问题:除了offsetExists仅在5.3.0中可用之外,2之间有什么区别?


我进行的小测试......

$s = new SplObjectStorage();
$o1 = new StdClass();
$o2 = new StdClass();
$o3 = "I'm not an object!";
$s->attach($o1);

var_dump($s->contains($o1));
var_dump($s->offsetExists($o1));
echo '<br>';
var_dump($s->contains($o2));
var_dump($s->offsetExists($o2));
echo '<br>';
var_dump($s->contains($o3));
var_dump($s->offsetExists($o3));
Run Code Online (Sandbox Code Playgroud)

输出:

boolean true
boolean true

boolean false
boolean false

Warning: SplObjectStorage::contains() expects parameter 1 to be object, string given in index.php on line 15
null

Warning: SplObjectStorage::offsetExists() expects parameter 1 to be object, string given in index.php on line 16
null
Run Code Online (Sandbox Code Playgroud)

Lei*_*igh 13

它们都完全一样.

offsetExists被定义为方法的别名,contains并且仅为了符合ArrayAccess接口而包括在内.

您可以在源中看到SPL_MA(方法别名)正在使用,并且还设置了几个其他别名.

  • offsetExists =包含
  • offsetSet = attach
  • offsetUnset = detach