切换PHP 8后sizeof()函数报Type TypeError参数类型错误求助
解决PHP 8中sizeof()的TypeError问题
问题原因
PHP 8对sizeof()(count()的别名)的参数类型做了严格限制,要求必须是Countable类型或数组。而WordPress的get_the_terms()函数在以下场景会返回非可数类型:
- 没有找到对应术语时返回
false - 参数错误或术语不存在时返回
WP_Error对象
直接把这些结果传给sizeof()就会触发TypeError。
修复方案
方案1:用is_countable()统一判断(推荐,PHP7.3+兼容)
先获取术语结果,检查是否可数后再计数:
$terms = get_the_terms( $post->ID, 'product_brands' ); $brand_count = is_countable( $terms ) ? sizeof( $terms ) : 0;
方案2:针对WordPress的精准判断
考虑到get_the_terms()可能返回WP_Error,可以先单独处理错误情况:
$terms = get_the_terms( $post->ID, 'product_brands' ); if ( is_wp_error( $terms ) || !$terms ) { $brand_count = 0; } else { $brand_count = sizeof( $terms ); }
注意
两种方案都避免了直接将不确定类型的变量传入sizeof(),确保只有可数类型才会被计数,非可数情况默认返回0。
内容的提问来源于stack exchange,提问作者FallingBrick
相关产品推荐
相关产品推荐

