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 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集