Can I use a function as the default value of an argument in another function? In the example below, I'm trying to use the Wordpress function get_the_title()
as the default value:
function GetPageDepartment($department = get_the_title()) {
return $department;
}
As is, the parentheses are causing a parse error. Is there a way around this, or would I have to pass the function value to a variable somewhere outside of the default values?
I know the actual code here would be largely pointless as it just returns get_the_title()
, but it's just as an example, as what I actually do with the argument isn't that relevant to the question.
The answer is "no and yes, but ... yet...".
No, using PHP 5.6 you can't assign a function as a default value of a function/method.
Yes, you can assign a string and if you use that parameter/variable in a function context, i.e. echo $department();
, the string will be treated as the name of a function and get_the_title()
will be invoked. But... it's kinda ugly that you have to rely on the string->function name relation. Yet ... who cares?
edit: for your consideration....
<?php
function get_the_title() { return "the title"; }
function GetPageDepartment( callable $department=null ) {
if ( null==$department ) {
$department = 'get_the_title';
}
return '<'.$department().'>';
}
echo GetPageDepartment();
No you can't use this code
<?php
function get_the_title(){
return 'this is the title';
}
$temp = get_the_title();
function GetPageDepartment($department) {
echo $department;
}
GetPageDepartment($temp);
In the end, I plumped for:
function GetPageDepartment($department = null) {
$department = $department ?: get_the_title(); //Sets value if null.
}
which sets the value of $department to get_the_title() if no other value's set.