PHP如何将参数传递给常量

nen*_*007 5 php

我正在寻找一个将参数传递给动态常量Name的解决方案.

 <?php 
 class L {
   const profile_tag_1 = 'Bla bla Age from %s to %s';
   const profile_tag_2 = 'Wow Wow Age from %s to %s';

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

我的代码

 $x = 1;
 echo constant("L::profile_tag_".$x); // arguments: 20, 30
Run Code Online (Sandbox Code Playgroud)

我想得到

 Bla bla Age from 20 to 30
Run Code Online (Sandbox Code Playgroud)

我怎样才能将我的两个论点传递给它?

dyn*_*mic 6

您可以使用func_get_args()array_shift()隔离常量字符串名称.
[ 键盘直播 ]

<?php 
 class L {
   const profile_tag_1 = 'Bla bla Age from %s to %s';
   const profile_tag_2 = 'Wow Wow Age from %s to %s';

   public static function __callStatic() {
      $args = func_get_args();
      $string = array_shift($args);
      return vsprintf(constant('self::' . $string), $args);
   }
 }


L::__callStatic('profile_tag_1',12,12);
Run Code Online (Sandbox Code Playgroud)

但是,请注意当使用此函数与静态方法的泛型调用时,您需要更改__callStatic签名以允许$name$arguments像这样:

 class L {
   const profile_tag_1 = 'Bla bla Age from %s to %s';
   const profile_tag_2 = 'Wow Wow Age from %s to %s';

   public static function __callStatic($name, $args) {
      $string = array_shift($args);
      return vsprintf(constant('self::' . $string), $args);
   }
 }


L::format('profile_tag_1',12,12);
Run Code Online (Sandbox Code Playgroud)

一个更好的方法

虽然,有一种更好的方法来执行你需要的东西(在评论中阅读Yoshi),考虑到你正在使用静态的东西:

 echo sprintf(L::profile_tag_1,12,14);
Run Code Online (Sandbox Code Playgroud)

你现在甚至都不需要Class.

  • 甚至不需要使用`__callStatic`.一个好的*可读名称也可以.不需要魔法.例如`L :: format(L :: profile_tag_1,20,30);`(imo) (5认同)
  • @dynamic这是一个非常有用的答案.谢谢. (2认同)