PHP passes the default argument to the function

I have a PHP function, for example:

function($foo = 12345, $bar = false){} 

What I want to do is call this function with the default argument $ foo, but $ bar is set to true, for example (more or less)

 function(DEFAULT_VALUE, true); 

How can I do it? How to pass an argument as the default value for a function without knowing this value?

Thanks in advance!

+4
source share
5 answers

This is not possible initially in PHP. There are workarounds, such as using arrays to pass all parameters instead of a string of arguments, but they have massive flaws .

The best manual workaround I can think of is to define a constant with an arbitrary value that cannot run into a real value. For example, for a parameter that can never be -1 :

 define("DEFAULT_ARGUMENT", -1); 

and test this:

 function($foo = DEFAULT_ARGUMENT, $bar = false){} 
+9
source

The usual approach to this is that the if (is_null($foo)) function replaces it by default. Use an empty string, etc., to skip arguments. Here's how most of the PHP built-in functions do, which should pass arguments.

 <?php function($foo = null, $bar = false) { if (is_null($foo)) { $foo = 12345; } } ?> 
+2
source

PHP cannot do this, so you have to get around this. Since you already need a function in the current form, just define another:

 function blah_foo($bar) { blah(12345, $bar); } function blah($foo = 12345, $bar = false) { } 
+2
source

put them the other way:

 function($bar = false, $foo = 12345){} function(true); 
+1
source

I think it’s better sorted based on the argument that changed most often, $bar , for example, we put it first,

 function foo( $bar = false, $foo = 12345){ // blah blah... } 

so if you want to pass $bar to true and $foo to 12345 , you do this,

 foo(true); 
-1
source

Source: https://habr.com/ru/post/1334376/


All Articles