dscrn1974 2012-03-13 04:32
浏览 20
已采纳

PHP类 - 获取非对象和未定义通知的属性

*edit have fixed this code - see inline comments marked EDIT *

I'm getting a few PHP debug notices when using the following code in a wordpress theme. It's my first attempt at using a PHP class, and it does work ok, but the debug notices concern me. I am calling the method in my PHP template thus:

<?php $getjobmeta->job_type(); ?> & <?php $getjobmeta->post_types(); ?>

The debug notices are as follows:

Notice: Undefined variable: post

Notice: Trying to get property of non-object

From the research I have done this looks like an issue with the class sometimes returning a non object, so i tried wrapping the 'echo' in isset and is_object but I just can't fix those notices.

Here is the simplified code. For the sake of my sanity I could really use some help.

    // define the class

class getJobMeta { 

    var $jobmeta_echo; // set a class variable to store our echo

    public function job_type() { // define a class function and make it public

            global $post // EDIT IN FIX

          if ( 'post' == get_post_type() )  {       
                   $jobtype = get_the_term_list( $post->ID, 'job-type', '<span itemprop="employmentType">', ', ', '</span>', 0 ); // 0 at end of arg signifies that we don't want links outputted
                   }

          else { 
                    return ''; 
               }

     echo $jobtype.$this->jobmeta_echo;

     } // end function job_type

    // define post type


  public function post_types() { 

               global $post // EDIT IN FIX


        if ('post' == get_post_type())  {
                    $posttype = get_the_term_list( $post->ID, 'channel', '<strong class="channel-links clearfix">', ', ', '</strong>', 1); // 1 means output as link

            } elseif ( 'blog' == get_post_type() )  {
                $posttype = '<a href="/blog/" class="post-type-label">Blog</a>';

            } elseif ( 'type2' == get_post_type() )  {
                $posttype = '<a href="/type2/" class="post-type-label">Type2</a>';

        } else {
                $posttype = '';
        }


    echo $posttype.$this->jobmeta_echo;  // EDIT TYPO


    } // end function posttype


   } // end getJobMeta class

    // set the class into a variable
    $getjobmeta = new getJobMeta; 

Thanks Ben

展开全部

  • 写回答

2条回答 默认 最新

  • dty63504 2012-03-13 04:47
    关注

    You're asking about Wordpress here and $post is a global variable so you need to define it within your functions:

    public function job_type() {
        global $post;
        ...
    
    public function post_types() { 
        global $post;
        ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部