如果memcached正在运行,调用memcache_connect()返回一个对象实例,而不是布尔值。如果memcached没有运行,调用memcache_connect()会抛出一个通知和一个警告(并返回预期的false)。
<?php
/* memcache 正在运行 */
$test1 = memcache_connect('127.0.0.1',11211);
echo gettype($test1);
// object
echo get_class($test1);
// Memcache
/* memcached 已停止 */
$test2 = memcache_connect('127.0.0.1',11211);
/*
Notice: memcache_connect(): Server 127.0.0.1 (tcp 11211) failed with: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
(10060) in C:\Program Files\Support Tools\- on line 1
Warning: memcache_connect(): Can't connect to 127.0.0.1:11211, A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
(10060) in C:\Program Files\Support Tools\- on line 1
*/
echo gettype($test2);
// boolean
echo $test2===false;
// 1
?>
似乎没有办法检查memcached是否正在运行,而不诉诸于错误抑制。
<?php
$test3 = @memcache_connect('127.0.0.1',11211);
if( $test3===false ){
// memcached 可能没有运行
}
?>