Weakref::valid

(PECL weakref >= 0.1.0)

Weakref::valid参照先のオブジェクトがまだ存在するかどうかを調べる

説明

public Weakref::valid ( void ) : bool

参照先のオブジェクトがまだ存在するかどうかを調べます。

パラメータ

この関数にはパラメータはありません。

返り値

オブジェクトがまだ存在して Weakref::get() アクセス可能な場合に TRUE、 それ以外の場合に FALSE を返します。

参考

  • Weakref::get() - 弱い参照が指す先にオブジェクトを返す

add a note add a note

User Contributed Notes 1 note

up
0
d dot negrier at nospam dot thecodingmachine dot com
6 years ago
Beware that the "valid()" method should not be used to check the availability of an object before calling "get()". Indeed, the garbage collector might be triggered between the call to "valid()" and the call to "get()".

<?php

if ($weakRef->valid()) { // Returns true because the object is not yet garbage collected
    // If you are not lucky, the garbage collector might be triggered here
   
$obj = $weakRef->get(); // Returns null
   
$obj->doSomeStuff(); // Boom!
}
?>

So instead, you should always call "get()" directly:

<?php
$obj
= $weakRef->get();
if (
$obj !== null) {
   
$obj->doSomeStuff(); // This is 100% accurate
}
?>

Generally speaking, the "valid()" method is tricky because a call to it might return true and the next call might return false (you never know when the garbage collector will be trigerred). However, testing for invalidity works reliably.

<?php
if ($weakRef->valid()) {
   
// At this point, you are not sure that the object is still there (garbage collector might have collected it)
}

if (!
$weakRef->valid()) {
   
// At this point, you are sure the object is gone.
}
?>
To Top