Php 类静态属性的未设置数组项似乎不起作用
我试着为WordPress编写一个插件,它可以保存一些帖子。该数组包含在类的静态属性中 该类如下所示:Php 类静态属性的未设置数组项似乎不起作用,php,arrays,wordpress,class,static,Php,Arrays,Wordpress,Class,Static,我试着为WordPress编写一个插件,它可以保存一些帖子。该数组包含在类的静态属性中 该类如下所示: class my_class_name { private static $posts = array(); public function __construct() { add_action('template_redirect', array($this, 'get_posts')); } public function g
class my_class_name
{
private static $posts = array();
public function __construct()
{
add_action('template_redirect', array($this, 'get_posts'));
}
public function get_posts()
{
$args = array(...);
$my_posts = new WP_Query($args);
$my_posts = isset($my_posts->posts) && !empty($my_posts->posts) ? $my_posts->posts : array();
my_class_name::$posts = $my_posts;
}
public static function get_posts()
{
return my_class_name::$posts;
}
public static function unset_post($item_id)
{
unset(my_class_name::$posts[$item_id]);
}
}
$class_instance = new my_class_name();
在我的主题中,我有以下代码:
$my_posts = my_class_name::get_posts();
if(!empty($my_posts))
{
$key = array_rand($my_posts, 1);
$post = $my_posts[$key];
my_class_name::unset_post($key); // I have try this way
unset($dynamic_banners[$key]); // as well this way too
echo "<pre>";
print_r($my_posts);
echo "</pre>";
}
$my_posts=my_class_name::get_posts();
如果(!空($my_posts))
{
$key=array\u rand($my\u posts,1);
$post=$my_posts[$key];
我的_class_name::unset_post($key);//我尝试过这种方法
unset($dynamic_banner[$key]);//也是这样
回声“;
打印(我的帖子);
回声“;
}
但问题是具有给定ID的数组仍然存在于我的数组中。我做错什么了吗
这种情况有什么解决方案吗?数组在PHP中是按值传递的,因此
$my\u posts
与my\u class\u name::$posts
变量不同。您必须分别取消设置其中的值:
public static function &get_posts()
或者,您可以通过将get\u posts
声明为
$my_posts = &my_class_name::get_posts();
然后做什么
我还尝试通过引用检索valies,但仍然是相同的问题。例如:$my_posts=&my_class_name::get_posts();假设将该方法声明为
公共静态函数&get_posts()
,并执行$my_posts=&my_class_name::get_posts()代码>进行引用。
$my_posts = &my_class_name::get_posts();