代码之家  ›  专栏  ›  技术社区  ›  helgatheviking

从其他文件调用PHP类

  •  3
  • helgatheviking  · 技术社区  · 16 年前

    我正在处理一些自定义的日志类型。我完成了第一个任务,意识到我使用的元数据库代码可以被其他、未来、自定义的日志类型(以及页面、日志等)重用。所以我把这个类放在它自己的PHP文件中,并把它从我的子主题的functions.php文件中包含进来。我以前从未使用过类,但我想我可以从我想要的任何地方调用该类,因为这是我为函数所做的。相反,我从post-types.php文件调用它,并得到以下错误:

    “致命错误:在第73行的d:\helga\xampp\htdocs\plagueround\wp content\themes\plagueround\new2\functions\post-types.php中找不到类'my'u meta'box'”

    在子主题的functions.php中,我包含了类所在的文件:

    define('CHILDTHEME_DIRECTORY', get_stylesheet_directory() . '/');
    // Meta Box Class - makes meta boxes
    require_once(CHILDTHEME_DIRECTORY . 'functions/meta_box_class.php');
    

    这是我的课

    //My Meta Box CLASS
    //from: http://www.deluxeblogtips.com/2010/05/howto-meta-box-wordpress.html
    
    class My_meta_box {
    
            protected $_meta_box;
    
            // create meta box based on given data
            function __construct($meta_box) {
            $this->_meta_box = $meta_box;
            add_action('admin_menu', array(&$this, 'add'));
    
            add_action('save_post', array(&$this, 'save'));
        }
    
        /// Add meta box for multiple post types
        function add() {
            foreach ($this->_meta_box['pages'] as $page) {
                add_meta_box($this->_meta_box['id'], $this->_meta_box['title'], array(&$this, 'show'), $page, $this->_meta_box['context'], $this->_meta_box['priority']);
            }
        }
    
        // Callback function to show fields in meta box
        function show() {
            global $post;
    
            // Use nonce for verification
            echo '<input type="hidden" name="mytheme_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';
    
            echo '<table class="form-table">';
    
            foreach ($this->_meta_box['fields'] as $field) {
                // get current post meta data
                $meta = get_post_meta($post->ID, $field['id'], true);
    
                echo '<tr>',
                        '<th style="width:20%"><label for="', $field['id'], '">', $field['name'], '</label></th>',
                        '<td>';
                switch ($field['type']) {
                    case 'text':
                        echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:97%" />',
                            '<br />', $field['desc'];
                        break;
                    case 'textarea':
                        echo '<textarea name="', $field['id'], '" id="', $field['id'], '" cols="60" rows="4" style="width:97%">', $meta ? $meta : $field['std'], '</textarea>',
                            '<br />', $field['desc'];
                        break;
                    case 'select':
                        echo '<select name="', $field['id'], '" id="', $field['id'], '">';
                        foreach ($field['options'] as $option) {
                            echo '<option', $meta == $option ? ' selected="selected"' : '', '>', $option, '</option>';
                        }
                        echo '</select>';
                    break;
                    case 'select2': //for when value and display text don't match
                                    //$options array must be multidimensional with both the 'value' and the 'text' for each option
                                    //for example = array( array(text=>text1,value=>value1),array(text=>text2,value=>value2))
                                    //then in <option> value = $option['value'] and text = $option['text']
                        echo '<select name="', $field['id'], '" id="', $field['id'], '">';
                        foreach ($field['options'] as $option) {
                            echo '<option value="',$option['value'],'"', $meta == $option['value'] ? ' selected="selected"' : '', '>', $option['desc'], '</option>';
                        }
                        echo '</select>';
                        break;
                    case 'radio':
                        foreach ($field['options'] as $option) {
                            echo '<input type="radio" name="', $field['id'], '" value="', $option['value'], '"', $meta == $option['value'] ? ' checked="checked"' : '', ' />', $option['name'];
                        }
                        break;
                    case 'checkbox':
                        echo '<input type="checkbox" name="', $field['id'], '" id="', $field['id'], '"', $meta ? ' checked="checked"' : '', ' />';
                        break;
                }
                echo    '<td>',
                    '</tr>';
            }
    
            echo '</table>';
        }
    
        // Save data from meta box
        function save($post_id) {
            // verify nonce
            if (!wp_verify_nonce($_POST['mytheme_meta_box_nonce'], basename(__FILE__))) {
                return $post_id;
            }
    
            // check autosave
            if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
                return $post_id;
            }
    
            // check permissions
            if ('page' == $_POST['post_type']) {
                if (!current_user_can('edit_page', $post_id)) {
                    return $post_id;
                }
            } elseif (!current_user_can('edit_post', $post_id)) {
                return $post_id;
            }
    
            foreach ($this->_meta_box['fields'] as $field) {
                $old = get_post_meta($post_id, $field['id'], true);
                $new = $_POST[$field['id']];
    
                if ($new && $new != $old) {
                    update_post_meta($post_id, $field['id'], $new);
                } elseif ('' == $new && $old) {
                    delete_post_meta($post_id, $field['id'], $old);
                }
            }
        }
    }
    

    然后,在我的post-types.php文件中,我为一个自定义的post类型定义了一些元框:

    $prefix = '_events_';
    $post_id = $_GET['post'] ? $_GET['post'] : $_POST['post_ID'] ;
    
    $events_meta_box = array(
        'id' => 'wpt_events',
        'title' => 'Events Options',
        'pages' => array('events'), // multiple post types possible
        'context' => 'side',
        'priority' => 'low',
        'fields' => array(
            array(
                'name' => 'Headline',
                'desc' => 'Enter the heading you\'d like to appear before the video',
                'id' => $prefix . 'heading1',
                'type' => 'text',
                'std' => ''
            ),
    
        )
    
    );
    
    $my_box = new My_meta_box($events_meta_box); 
    

    那么-如何引用其他文件中的类?

    编辑/继续

    只需将require-once语句移到post-types.php(尝试调用类的语句)就可以了。但我还是尝试了自动加载脚本。

    function __autoload($className)
    {
            require(CHILDTHEME_DIRECTORY .'functions/class_' . $className . '.php')  ;
    }
    

    在这里,我将类文件重命名为class\u my meta\u box.php,而我的\u meta\u box是类名。

    导致以下错误: 警告:require(d:\helga\xampp\htdocs\plagueround/wp content/themes/plagueround_new/functions/class_wp_user_search.php)【function.require】:无法打开流:在d:\helga\xampp\htdocs\plagueround\wp content\themes\plagueround_new\functions.php的第66行没有这样的文件或目录。

    致命错误:require()[function.require]:在第66行打开必需的'd:\helga\xampp\htdocs\plagueround/wp content/themes/plagueround'u new/functions/class'u wp'u user'u search.php'(包括'u path=.;d:\helga\xampp\php\pear')失败。

    我不完全理解它说的是什么,但我认为它正在尝试自动加载一些默认的wordpress类…在我的目录中查找它显然不存在。

    4 回复  |  直到 15 年前
        1
  •  4
  •   Community Mohan Dere    9 年前

    实际上,文件是否包含类或其他内容并不重要。为了让PHP能够从其他文件执行代码,PHP必须知道文件在哪里,所以它是 require 或 include .

    例子:

    // foo.class.php
    class Foo {}
    
    // main.php
    require_once '/path/to/foo.class.php';
    $foo = new Foo;
    

    当使用类时,它实际上是有意义的 use a Naming Convention 使用一个 Autoloader 如此 PHP will try to include the class on it's own 不需要你要求或包括它。

        2
  •  1
  •   JJD    15 年前

    你可以用常数 WP_PLUGIN_DIR 描述路径。

    // Foo.class.php
    class Foo {}
    
    // main.php
    require_once WP_PLUGIN_DIR.'/Foo.class.php';
    $foo = new Foo;
    
        3
  •  0
  •   websch01ar    16 年前

    只需使用绝对路径:

    require_once("fullpath/functions/meta_box_class.php") or die ("Could Not load file");
    
        4
  •  0
  •   Lethargy    16 年前

    看起来像 meta_box_class.php 不包括在内。要了解在任何时候包含了哪些文件,请尝试:

    var_dump(get_included_files());