dongmei8071 2014-11-05 00:22
浏览 42
已采纳

带参数的PHP vsprintf

I have the following class:

<?php 
    class L {
        const login = 'Login';
        const title_404 = '404';
        const title_dyn = 'Title: %s';
        const page_dyn = 'Page: %s - %s';

        public static function __callStatic($string, $args) {
           vsprintf(constant("self::" . $string), $args);
        }
    }

It won't replace %s by passed arguments:

    L::login; --> Login
    L::title_404; --> 404
    L::title_dyn('test'); --> empty
    L::page_dyn('test', 'more'); --> empty
    L::login(); --> empty

I should get with L::title_dyn('test'); --> "Title: test"

What I'm doing wrong?

  • 写回答

1条回答 默认 最新

  • dsklzerpx64815631 2014-11-05 10:49
    关注

    Presumably your full testcase is something like this:

    <?php 
    class L {
        const login = 'Login';
        const title_404 = '404';
        const title_dyn = 'Title: %s';
        const page_dyn = 'Page: %s - %s';
    
        public static function __callStatic($string, $args) {
           vsprintf(constant("self::" . $string), $args);
        }
    }
    
    echo L::login . "
    ";                    // "Login"
    echo L::title_404 . "
    ";                // "404"
    echo L::title_dyn('test') . "
    ";        // (empty)
    echo L::page_dyn('test', 'more') . "
    "; // (empty)
    echo L::login() . "
    ";                  // (empty)
    

    (next time, write this in the question please)

    The first two work because you're not using function-call syntax, so the constants are echo'd as-is.

    The latter three are empty because, although __callStatic does its work, it then completely discards that work: you never return the result of vsprintf. Recall that vsprintf does not output anything — it returns its result. You also did not write any echo in there. So, there is no value for your calling code to use, and no output from within the function itself. Presto, just as your problem says.

    You almost certainly want to do this:

        public static function __callStatic($string, $args) {
           return vsprintf(constant("self::" . $string), $args);
        }
    

    Live demos: broken, working

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

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示