Why can I not use $this in function arguments default value - php

I trying to pass a parameter in codeigniter.
This works for me:
function the_kwarg($gender){
$gender = $this->uri->segment(3);
}
However,i don't understand why this is wrong
function the_kwarg($gender=$this->uri->segment(3)){
//$gender = $this->uri->segment(3);
}
Why is it wrong to do it that way?.

Because functions can only accept scalar default values, it can't evaluate $this (or any variable) in that context.
From the manual:
A function may define C++-style default values for scalar arguments.
And:
The default value must be a constant expression, not (for example) a variable, a class member or a function call.

Function arguments default values cannot be a dynamic expression, e.g.
function foo ($x = 1 + 1) { }
is illegal, because 1 + 1 is an expression. We all know the result is a constant 2, but PHP isn't smart, and just sees an expression.

While people already gave you correct answers, I can give you an example how to solve the problem:
function the_kwarg($gender = null){
$gender = (!is_null($gender)) ? $gender : $this->uri->segment(3);
}

Why don't you just use the function like
function the_kwarg($gender){
echo $gender; // will echo male
}
// http://www.example.com/controller/the_kwarg/male
In CI the uri segments after the function name are basically the parameters of the function

Related

What does the parameter $something=null mean in PHP?

We got a PHP file in school with some functions and one of them is the following:
function serviceRec($db,$table,$afields=null,$avalues=null){ .... }
My question: What does the $afields=null and $avalues=null mean?
Thank you!
function serviceRec($db,$table,$afields=null,$avalues=null){ .... }
It means that, when you call your function and don't pass those parameters then it'll by default place value as null
Example :
function hello($name = "anonymous"){
return "Hello $name \n";
}
echo hello();//Hello anonymous
echo hello("BigSeeProduction");//Hello BigSeeProduction
DOCS
These assignments are default values. If you were to call the function as e.g.
serviceRec($a, $b)
the omitted parameters would be assumed to be null. If, on the other hand, you called the function as e.g.
serviceRec($a, $b, $c, $d)
$afields would be set to $c and $avalues to $d.
Of course, you could also call with 3 parameters.
It Means it's the default value. So when u don't fill this parameter it will be set as null.
See the man here :
PHP.net : default value function
That indicates, that if you leave that parameter out(Don't specify it at all), the value after the =, in this case null is used. So if you don't care about these parameters just leave them out. It has the same effect as just supllying null.

Define variable within function parameter value

I wanted to know whether i can pass a globally defined variable within a function parameter value. e.g.
$tweetsdisplayed = 40;
function display_latest_tweets(
$twitter_user_id,
$cache_file = './tweets.txt',
$tweets_to_display = $tweetsdisplayed)
{
Currently, the option above is not working, even when i dont pass it as a variable tweetsdisplayed. Whats the best way of doing this?
Thanks in advance
PHP Manual says:
The default value must be a constant
expression, not (for example) a
variable, a class member or a function
call.
but you can use $_GLOBALS.
e.g.:
$tweetsdisplayed = 40;
function display_latest_tweets(
$twitter_user_id,
$cache_file = './tweets.txt',
$tweets_to_display = null)
{
$tweets_to_display = isset($tweets_to_display) ? $tweets_to_display : $_GLOBALS['tweetsdisplayed'];
}

PHP - Why is it not possible to use ~PHP_INT_MAX as a default argument

I'm wrote a function in which I was using PHP_INT_MAX and ~PHP_INT_MAX as the default arguments but I ended up getting a syntax error for '~'. The declaration is:
public static function isNumberValid($number, $lowerbound = ~PHP_INT_MAX, $upperbound = PHP_INT_MAX)
I fixed it by making $lowerbownd = null in the declaration and then setting it in the body and now it works perfectly fine:
if (is_null($lowerbound)){
$lowerbound = ~PHP_INT_MAX;
}
I was just wondering why that is..
The default value of an optional variable has to be constant, like the initial value of variables or constants in a class, for example. ~PHP_INT_MAX is not a constant, it’s an expression. (You can’t use, say, 2 + 2, either.)
There’s was an RFC relating to this.
The default value of an argument has to be a constant. If you want to use ~PHP_INT_MAX you can define another constant with that value and use this constant:
define('PHP_INT_MIN', ~PHP_INT_MAX);
public static function isNumberValid($number, $lowerbound = PHP_INT_MIN, $upperbound = PHP_INT_MAX)
Default values for function parameters must be a constant value. They cannot be an expression. Even though PHP_INT_MAX is a compiled-in-value and available to the compiler immediately, you're still causing that to be an expression by doing the bit-wise NOT operation.
function foo ($x = PHP_INT_MAX) { echo 'this is ok'; }
function bar ($x = ~PHP_INT_MAX) { echo 'this is NOT ok'; }

PHP function with variable as default value for a parameter

By default a PHP function uses $_GET variables. Sometimes this function should be called in an situation where $_GET is not set. In this case I will define the needed variables as parameter like: actionOne(234)
To get an abstract code I tried something like this:
function actionOne($id=$_GET["ID"])
which results in an error:
Parse error: syntax error, unexpected T_VARIABLE
Is it impossible to define an default parameter by using an variable?
Edit
The actionOne is called "directly" from an URL using the framework Yii. By handling the $_GET variables outside this function, I had to do this on an central component (even it is a simple, insignificant function) or I have to change the framework, what I don't like to do.
An other way to do this could be an dummy function (something like an pre-function), which is called by the URL. This "dummy" function handles the variable-issue and calls the actionOne($id).
No, this isn't possible, as stated on the Function arguments manual page:
The default value must be a constant
expression, not (for example) a
variable, a class member or a function
call.
Instead you could either simply pass in null as the default and update this within your function...
function actionOne($id=null) {
$id = isset($id) ? $id : $_GET['ID'];
....
}
...or (better still), simply provide $_GET['ID'] as the argument value when you don't have a specific ID to pass in. (i.e.: Handle this outside the function.)
function actionOne( $id=null ) {
if ($id === null) $id = $_GET['ID'];
}
But, i would probably do this outside of the function:
// This line would change, its just a for instance
$id = $id ? $id : $_GET['id'];
actionOne( $id );
You should get that id before you call the function. Checking for the existence of the parameter breaks encapsulation. You should do something like that:
if (isset($_GET["ID"])
{
$id = $_GET["ID"];
}
else
{
//$id = something else
}
function doSomethingWithID($id)
{
//do something
}
You could use constant variable
define('ID',$_GET["ID"]);
function($id = _ID_){
//code
}
Yes it is impossible.
The default has to be a static variable:
function actionOne( $id='something') {
//code
}
Easy peanuts! (Might contain minor mistakes, errors or typos!)
You need a helper function, which will call you main function recursively, but having NULL as default:
Wrong: function actionOne($id=$_GET["ID"])
Right:
function actionOne($id) {...}
function actionOnewithID($id=NULL) {
if (NULL==$id){actionOne($_GET["ID"]);}
else {actionOne($id);
}
And if you need to return a value:
function actionOne($id) {...}
function actionOnewithID($id=NULL) {
if (NULL==$id){return(actionOne($_GET["ID"]));}
else {return(actionOne($id));
}
I hope this helps!
shortest way is:
function actionOne($id = null)
{
$id = $id ?? $_GET["ID"];
...
}

create_function with default parameter values?

Ok, I'm looking into using create_function for what I need to do, and I don't see a way to define default parameter values with it. Is this possible? If so, what would be the best approach for inputting the params into the create_function function in php? Perhaps using addslashes?
Well, for example, I have a function like so:
function testing($param1 = 'blah', $param2 = array())
{
if($param1 == 'blah')
return $param1;
else
{
$notblah = '';
if (count($param2) >= 1)
{
foreach($param2 as $param)
$notblah .= $param;
return $notblah;
}
else
return 'empty';
}
}
Ok, so how would I use create_function to do the same thing, adding the parameters and their default values?
The thing is, the parameters are coming from a TEXT file, as well as the function itself.
So, wondering on the best approach for this using create_function and how exactly the string should be parsed.
Thanks :)
Considering a function created with create_function this way :
$func = create_function('$who', 'echo "Hello, $who!";');
You can call it like this :
$func('World');
And you'll get :
Hello, World!
Now, having a default value for a parameter, the code could look like this :
$func = create_function('$who="World"', 'echo "Hello, $who!";');
Note : I only added the default value for the parameter, in the first argument passed to create_function.
And, then, calling the new function :
$func();
I still get :
Hello, World!
i.e. the default value for the parameter has been used.
So, default values for parameters work with create_function just like they do for other functions : you just have to put the default value in the list of parameters.
After that, on how to create the string containing the parameters and their values... A couple of string concatenations, I suppose, without forgetting to escape what should be escaped.
Do you want to create an anonymous function? The create_function is used to create the anonymous functions. Otherwise you need to create function normally like:
function name($parms)
{
// your code here
}
If you want to use the create_function, here is the prototype:
$newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
echo "New anonymous function: $newfunc\n";
echo $newfunc(2, M_E) . "\n";
// outputs
// New anonymous function: lambda_1
// ln(2) + ln(2.718281828459) = 1.6931471805599
I'm having the same problem, trying to pass an array to a created callback function... I think I'll create a temporary variable... It's ugly but I have better to do then torture myself with slashes, my code is already cryptic enough the way it is now.
So, to illustrate:
global $tmp_someArray;
$tmp_someArray = $someArray;
$myCallback = create_function(
'$arg1',
'
global $tmp_someArray;
// do stuff with $tmp_someArray and $arg1....
return($something);
'
);

Categories