我已经尝试了几个小时修复以下方法的bug,不知道为什么它总是返回字符串而不是整数。
如果存在,则返回一个类属性;如果不存在,则返回一个临时值(并为下一次访问设置类属性)。
public static function get_number( $post_id = null ) {
// Check if class property already exists
if ( empty( self::$number ) ) {
// THIS IS ALWAYS STRING - WHY?
$number = get_transient( \'my_number\' );
if ( false === $number && $post_id ) {
$number = get_post_meta( $post_id, \'my_number\', true );
if ( \'\' !== $number ) {
$number = intval( $number );
// THERE GOES THE INTEGER
set_transient(\'my_number\', $number, 20 );
}
}
self::$number = $number;
// Should still be an integer since we\'ve never set any strings to transient
}
return self::$number;
}
奇怪的是当我用有效的
post_id
, 我会得到一个整数,但如果没有,我会得到一个字符串。
所以
gettype( get_number( 123 ) ) === \'integer\'
gettype( get_number() ) === \'string\'
Working Code (based on Otto\'s answer)
public static function get_number( $post_id = null ) {
// Check if class property already exists
if ( empty( self::$number ) ) {
// THIS IS ALWAYS STRING - WHY?
$number = get_transient( \'my_number\' );
if ( false === $number && $post_id ) {
$number = get_post_meta( $post_id, \'my_number\', true );
if ( \'\' !== $number ) {
// THERE GOES AN ARRAY OF THE INTEGER
set_transient(\'my_number\', array( intval( $number ) ), 20 );
self::$number = intval( $number );
return intval( $number );
}
}
self::$number = isset( $number[ 0 ] ) ? $number[ 0 ] : \'\';
}
return self::$number;
}