function functionName(if clause here) possible? - php

function getTemplate($tpl if ($vars) echo ", $vars";)...function
Is this possible somehow?
The above wont work.
Thanks

Optional arguments with default values
It looks like you want an optional argument, which you can accomplish by defining a default value in the function definition:
function getTemplate($tpl, $vars=null)
{
}
You can call this function as getTemplate($foo) or getTemplate($foo,$bar). See the PHP manual page on function arguments for more details.
Variable numbers of arguments
It's also possible to write functions which take a variable number of arguments, but you need to use func_num_args, func_get_arg and func_get_args functions to get at them. Here's an example from the manual
<?php
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs<br />\n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "<br />\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
}
}
foo(1, 2, 3);
?>
Calling a function with a variable number of parameters
To round off this answer even more, suppose you'd build an array of 1..n values and wanted to pass it to the foo() function defined above? You'd use call_user_func_array
$values=(1,2,3,4);
call_user_func_array('foo', $values);
This is the equivalent of calling
foo(1,2,3,4);

What's so bad about
function getTemplate($tpl, $vars=null) {}
?

if ($vars) { getTemplate($tpl, $vars); }
else {{ getTemplate($tpl, null); }
(semi-pseudo code)

Or:
getTemplate($tpl, ($vars)?$vars:null); // not sure
getTemplate($tpl, (!empty($vars))?$vars:null);
Also, if you would like a technique similar to echo:
$code = "getTemplate($pl";
if ( $vars ) { $code = $code . ", $vars);"; }
else { $code = $code . ");"; }
$ret = eval($code);
Although this is usually considered bad practice (never say never).
Please note that all code sent to eval will be executed directly. So don't put user input in an eval() call.

Related

Can I use PHP anonymous function as an argument, without assigning the function to a variable?

Does PHP allow the use of an anonymous function as one of the arguments during concatenation?
If so, what is the proper syntax?
For example, here's an example of what I want to get to work:
$final_text = $some_initial_string . function ($array_of_strings)
{
$out = '';
foreach ($array_of_strings as $this_particular_string)
{
$out .= $this_particular_string;
}
return $out;
};
Note: the below is expected to work for PHP Version 7.x but does not work on PHP Version 5.6 (For 5.6, first assign the anonymous function to a variable)
/*
* Strings before & after
*/
$table_heading_text = "HEADING";
$table_bottom_text = "BOTTOM";
/*
* Use the function this way
*/
echo $table_heading_text . (function (array $array_of_strings)
{
$out = '';
foreach ($array_of_strings as $this_particular_string)
{
$out .= $this_particular_string;
}
return $out;
})(array(
"hi",
"mom"
)) . $table_bottom_text;
In short ...
function must return some value that can be converted to text
function definition must be enclosed in parenthesis ( ... )
Don't forget to have calling arguments after the function definition
Examples:
echo "BEFORE" . (function ($x){return $x;})(" - MIDDLE - ") . "AFTER";
echo "BEFORE" . (function (){return " - MIDDLE - ";})() . "AFTER";
Also, using implode() may be better for this particular task.

Can 'if X, then echo X' be shortened in PHP?

The shortest way to echo out stuff in views in PHP - when not using template engines - is, afaik, this one:
<?php if (!empty($x)) echo $x; ?>
For a deeper explanaition why using !empty is a good choice please look here.
Is it possible to write this without writing the variable name twice (like in other languages), something like
!echo $x;
or
echo? $x;
echo #$x;
It's not exactly the right way to do it, but it is shorter.
it reduces the need to check if $x exists since # silences the error thrown when $x == null;
edit
echo empty($x) ? "" : $x;
is a shorter way, which is not really that much shorter nor does it solve your problem.
guess the other answers offer a better solution by addressing to make a short function for it.
Built in? No.
However - you could write your own wrapper function to do it:
$x = 'foobar';
myecho($x); // foobar
function myecho($x) {
echo !empty($x) ? $x : '';
}
This fits the bill of "only writing the variable once", but doesn't give you as much flexibility as the echo command does because this is a function that is using echo, so you can't do something like: myecho($x . ', '. $y) (the argument is now always defined and not empty once it hits myecho())
Easy approach would be to define an helper function so:
function mEcho($someVariable) {
if(!empty($someVariable) echo $someVariable;
}
I'm not sure though if that's what you intended.
Yes, you can write a function:
function echoIfNotEmpty($val) {
if (!empty($val)) {
echo $val;
}
}
Usage:
echoIfNotEmpty($x);
Sure you can shorten the function name.
If you don't know, if the var is intialized you can also do:
function echoIfNotEmpty(&$val = null) {
if (!empty($val)) {
echo $val;
}
}
Most times we want do prefix and append something
function echoIfNotEmpty(&$val = null, $prefix = '', $suffix = '') {
if (!empty($val)) {
echo $prefix . $val . $suffix;
}
}
echoIfNotEmpty($x, '<strong>', '</strong>');

How do you transfer a lot of variables to a function in a PHP Script

Okay, I have one.php and two.php, I have a function on two.php but I have my variables on one.php, whats the best way to transfer a lot of variables to two.php?
I used function($variable1, $variable2, $variable3)'and for some reason it stopped working after I had 14 or more arguments.
Any ideas?
You could put the variables into an array, then pass the array to the function.
$array = array("var1" => "", "var2" => "", "var3" => "");
function process($input) {
$input['var1'];
$input['var2'];
$input['var3'];
}
process($array);
you can also put all variables in one.php. just include one.php in two.php. so the variables will be available in two.php and you can use it.
<?php include("one.php"); ?>
You can also use php func_get_args() for variable number of arguments -
Reference Example -
<?php
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs<br />\n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "<br />\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
}
}
foo(1, 2, 3);
?>
Source - func-get-args

How to simulate args inside a php file?

PHP file.php arg1 arg2
Now I want to hardcode arg1 and arg2 into file.php,how to do it?
I never tried it, but the arguments are contained in a certain array $argv. So you have to set those entries if you want to hardcode them:
$argc = 3; // number of arguments + 1
$argv[0] = 'file.php'; // contains script name
$argv[1] = 'arg1';
$argv[2] = 'arg2';
$argv is a reserved variable.
But note that the first two parameter that you specify via command line will always be overwritten by arg1 and arg2.
Instead, if you need these values always in your script you should define them as normal variables at the top of your script:
$var1 = 'arg1';
$var2 = 'arg2';
or even as constants:
define('CONST1', 'arg1');
define('CONST2', 'arg2');
If you only want to provide arg1, arg2 as parameter via the command line, then you can just access them via $argv[1] and $argv[2], no need to mess with $argv;
you would use argv() inside your php script to get the arguments
foreach ($argv as $args){
print $args."\n";
}
element 0 contains the script name. the rest are the arguments.
You want to test how many arguments to the function, then do something accordingly.
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs<br />\n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "<br />\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
}
}
foo(1, 2, 3);

PHP function structure issue

I have a function
function me($a, $b, $c, $d) {
}
I want to add all this in array by array_push is there a variable enable me do this in one step.
I want echo all this on ($a,$b,$c,$d) by foreach
I don't know it i will assume any variable in () will equal $anything
function me($a,$b,$c,$d){
foreach ($anything as $key => $value){
echo $value; // i want return $a,$b,$c,$d values
}
}
Any one understand what I want? I want foreach the function and I cant explain because I don't understand
function(void){
foreach(void) { }
}
I want foreach all variables between () OK in function**(void)**{
I guess that you are talking about variable number of arguments. This example below is from the php site and uses func_num_args to get the actual number of arguments, and func_get_args which returns an array with the actual arguments:
function me()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs<br />\n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "<br />\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
}
}
me (1, 2, 3);
You could try func_get_args(). Calling that will give you an array (numerically indexed) containing all of the parameter values.
I don't really understand what you are asking, though.
func_get_args() returns all arguments passed to the function.
You can use func_get_args() like Jasonbar says:
function a() {
foreach (func_get_args() as $param) {
echo $param;
}
}
a(1,2,3,4); // prints 1234
a(1,2,3,4,5,6,7); // prints 1234567

Categories