dongle7637 2014-04-14 04:51
浏览 35
已采纳

PHP - 使用静态函数的Namespaced插件

I'm trying to namespace my plugin functions by using a class and static functions. I'm getting the error:

Fatal error: Constructor Read_Time::read_time() cannot be static in /Applications/MAMP/htdocs/Wordpress/wp-content/plugins/readtime/readtime.php on line 41

class Read_Time {
public $options;

static public function init() {
    add_filter('wp_meta', __CLASS__ . '::post_text');
}

static private function post_text() {
    if(is_single()) {
        global $post;
        $content = $post->post_content;
        echo("<h1>" . self::read_time($content) . "</h1>");
    }
}

static private function word_count($to_count) {
    return str_word_count($to_count);       
}

static private function read_time($content) {
    $wpm = 200;
    $int_minutes = ceil( self::word_count($content) / $wpm );
    if($int_minutes == 1) {
        return $int_minutes . " minute";
    } 
    else {
        return $int_minutes . " minutes";
    }       
}
}       
add_action('init', 'Read_Time::init');

Can someone tell me what I'm doing wrong?

  • 写回答

1条回答 默认 最新

  • douyan1321 2014-04-14 04:56
    关注

    PHP is interpreting your method read_time as a constructor for the class Read_Time, because it is not case-sensitive. The constructor cannot be static.

    From the online documentation:

    As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.

    Example #2 Constructors in namespaced classes

    <?php
    namespace Foo;
    class Bar {
        public function Bar() {
            // treated as constructor in PHP 5.3.0-5.3.2
            // treated as regular method as of PHP 5.3.3
        }
    }
    ?>
    

    P.S. If you really are using a version of PHP < 5.3.3, you should strongly consider upgrading. A lot has changed, and older versions may have unpatched bugs.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法