Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP how I can pass arguments to constant

Tags:

php

I'm looking for a solution to pass arguments to a dynamic constant 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);
   }
 }

My code

 $x = 1;
 echo constant("L::profile_tag_".$x); // arguments: 20, 30

I want get

 Bla bla Age from 20 to 30

How can I pass my two arguments to it?

like image 765
nenad007 Avatar asked Nov 06 '14 10:11

nenad007


People also ask

How will you passing an argument to a function in PHP?

PHP Function ArgumentsArguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

What does ?: Mean in PHP?

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.

How can you pass a variable by reference in PHP?

Pass by reference: When variables are passed by reference, use & (ampersand) symbol need to be added before variable argument. For example: function( &$x ). Scope of both global and function variable becomes global as both variables are defined by same reference.


1 Answers

You can use func_get_args() and array_shift() to isolate the constant string name.
[Codepad live]

<?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);

But, be aware when using this function with a generic call to a static method, you need to change __callStatic signature to allow $name and $arguments like this:

 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);

A better way

Although, there is a better way to perform what you need (read Yoshi in comments), considering you are using everything static:

 echo sprintf(L::profile_tag_1,12,14);

You don't even need a Class at this point.

like image 82
dynamic Avatar answered Sep 21 '22 22:09

dynamic