使用自静态功能时出错

时间:2017-02-28 04:34:26

标签: php

我有一个示例代码:

class Assets {
    public static $my_static = '';    

    public static function custom_js()
    {
        return self::add_custom_js();
    }

    public static function add_custom_js($str)
    {
        return self::$my_static = $str;
    }
}

和php

<?php
Assets::add_custom_js("ABC");
?>
<html>
 ...
 <?php echo Assets::custom_js(); ?>
 ...
</html>

错误无法显示数据字符串&#34; ABC&#34;

2 个答案:

答案 0 :(得分:0)

我认为您希望在$my_static中返回ABC值以获取echo Assets::custom_js();。请考虑以下事项:

class Assets {
    public static $my_static = '';    

    public static function custom_js()
    {
        // return self::add_custom_js();
        return self::$my_static; //This is what you want i believe
    }

    public static function add_custom_js($str)
    {
        return self::$my_static = $str;
    }
}

答案 1 :(得分:0)

您必须从$my_static返回custom_js()所以您的课程应该如下:

<?php
class Assets {
    public static $my_static = '';    

    public static function custom_js()
    {
        return self::$my_static; //<-------------change this line
    }

    public static function add_custom_js($str="")
    {
        return self::$my_static = $str;
    }
}
?>