1

我通过使用命名空间从不同的文件夹自动加载 php 类。我使用命名空间并use获取所需的类名。但是发生了一个问题,需要类文件,因为我在new WP_Query()类中使用类并且该函数也希望包含WP_Query()类。

下面是代码..来自插件 index.php

namespace WPSEVENT;
use WPSEVENT\includes\Shortcode;

spl_autoload_register(__NAMESPACE__ . '\\autoload');

function autoload($class = '') {
    if (!strstr($class, 'WPSEVENT')) {
        return;
    }
    $result = str_replace('WPSEVENT\\', '', $class);
    $result = str_replace('\\', '/', $result);
    require $result . '.php';
}

并且包含文件夹中的简码类..

namespace WPSEVENT\includes;

/**
 * 
 */
class Shortcode
{
    public static $instance;

    public static function smartEventShortCode($atts){
        $vars = extract(shortcode_atts( 
            array(
                'columns' => 4,
                'style'   => 1, 
                'posts_per_page'    => 1,
            ), $atts ));

        $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
        $eventargs = array(
            'posts_per_page'    => $posts_per_page,
            'post_type'         => WP_SEVENT_SLUG,
            'paged'             => $paged,
        );

        $posts = new WP_Query($eventargs);
        $html = '<div class="row">';
        if($posts->have_posts()){
            while ($posts->have_posts()) {
                $posts->the_post();
                switch ($style) {
                    case '1':
                        //$html .= self::getStyleOne( $columns, $postdata );
                        break;
                }
            }
        }
        $html .= '</div>';
        return $html;
    }
}

我得到的错误

Fatal error: Class 'WPSEVENT\includes\WP_Query' not found

我期望的是排除WP_Query课程

4

1 回答 1

1

尝试:

new \WP_Query($eventargs);

或者,您可以在模板顶部设置它(在声明命名空间之后):

use WP_Query;

更多信息在这里

基本上,WP_Query它是全局命名空间的一部分,如果你不告诉 PHP 这个,它会尝试在当前命名空间中找到类 (WP_Query) 来调用它。

于 2018-06-09T04:02:26.957 回答