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'];
}
Related
I have to do a function that returns a string at contrary to another variable. I have a problem.
<?php
$parolaAlContrario="";
function ribaltaStringa($nome){
$lenght=strlen($nome);
for($i=0;$i<$lenght+4;$i++){
$parolaAlContrario[$i]=$nome[$lenght-1];
$lenght=$lenght-1;
}
echo implode($parolaAlContrario);
}
ribaltaStringa("marco"); ?>
This code returns 'ocram'. I don't understand why if I put implode($parolaAlContrario) outside the function the result is the variable $parolaAlContrario empty. Why?
This is because the scope of your variable is outside of your function. You need to assign the variable to whatever the result is from the function.
You should make your function return the variable, and assign it when complete.
function ribaltaStringa($nome)
{
$lenght = strlen($nome);
$parolaAlContrario = array();
for($i = 0; $i < $lenght + 4; $i++) {
$parolaAlContrario[$i] = $nome[$lenght - 1];
$lenght = $lenght - 1;
}
return implode($parolaAlContrario);
}
Notice, instead of echoing the variable, I return the variable. This allows us to assign the result to your variable once the function is finished.
I've also defined the variable $parolaAlContrario inside the function right outside the loop, this will allow you to return the value.
When you call the function, you should assign the variable again.
$parolaAlContrario = ribaltaStringa("marco");
Likewise, you could make a completely new variable with the word reversed by just changing the name of the variable during declaration; E.G:
$newVariable = ribaltaStringa("marco");
Why make it simple if you can make it complicated? You don't need to write your own function for that. Just use PHP's built-in function strrev() which reverses a string and you can save it to a new variable if you want:
$parolaAlContrario = strrev('marco');
Try it out:
https://3v4l.org/RmdE1
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
Edit: Made more clearer
I have a problem with a variable disappearing between function calls
firstly I start here with $pid being an int taken from a JSON string
print "PID".$pid."\n";
$a['points'] = Algorithm::getpredictionForPlayer($pid);
I get the output 'PID12' which is how it should be
Next in the Algorithm::getpredictionForPlayer
static function getpredictionForPlayer($pid)
{
print "PID2: ".$pid."\n";
$points =0;
for ($i = 0; $i < 10; $i++)
{
print "algorithm: ".$pid."\n";
$points += v4::predictPointsForPlayer($pid);
}
return intval($points/10);
}
Occasionally i get 'PID2: 12', but more often all that prints is 'PID2: '
Is there a reason the variable would disappear during this time?
Your variable in the global scope is $pid yet you are passing $player_id into the function
print "PID".$pid."\n";
$a['points'] = Algorithm::getpredictionForPlayer($player_id);
You've then got a parameter in your static method called $pid
static function getpredictionForPlayer($pid)
but this isn't the same as the variable in your global scope. In fact this will take the same value as the $player_id that you are passing in. If you want the $pid variable from your global scope to exist in the static method you should pass it in instead of $player_id.
btw, you should think about whether you really need a static method. Generally they make things hard to test and should be avoided if possible. Should you have a player object and call the method getPrediction() on that?
Change this line:
$a['points'] = Algorithm::getpredictionForPlayer($player_id);
To this:
$a['points'] = Algorithm::getpredictionForPlayer($pid);
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"];
...
}
I'm building a small abstract class that's supposed to make certain tasks easier.
For example:
$var = class::get('id');
would run check if there's pointer id in the $_GET, returning a string or array according to parameters. This should also work for post and request and maby more.
I'm doing it in the way there's function for all the superglobals. I'm using get as example:
get function gets a pointer as parameter, it calls fetchdata function and uses the pointer and "$_GET" as the parameters.
fetchdata is supposed to just blindly use the string it got as superglobal and point to it with the other param. Then check if it exists there and return either the value or false to get function, that returns the value/false to caller.
Only problem is to get the string work as superglobal when you don't know what it is. I did this before with a switch that checked the param and in case it was "get", it set $_GET to value of another variable. However I don't want to do it like that, I want it to be easy to add more functions without having to touch the fetchdata.
I tried $method = eval($method), but it didn't work. ($method = "$_GET"), any suggestions?
EDIT: Sorry if I didn't put it clear enough. I have a variable X with string value "$_GET", how can I make it so X gets values from the source described in the string?
So simply it's
$X = $_GET if X has value "$_GET"
$X = $_POST if X has value "$_POST"
I just don't know what value X has, but it needs to get data from superglobal with the same name than its value.
According to this page in the manual:
Note: Variable variables
Superglobals cannot be used as variable variables inside functions or class methods.
This means you can't do this inside a function or method (which you would be able to do with other variables) :
$var = '_GET';
${$var}[$key]
Instead of passing a string to fetchdata(), could you not pass $_GET itself? I think PHP will not copy a variable unless you modify it ('copy on write'), so this shouldn't use memory unnecessarily.
Otherwise there are only nine superglobals, so a switch-case as you have suggested isn't unreasonable.
You could do this with eval() if you really had to, something like:
eval('return $_GET;');
I think that would be unnecessary and a bad idea though; it is slow and you need to be extremely careful about letting untrusted strings anywhere near it.
Don't use eval. Just use reference.
//test value for cli
$_GET['test'] = 'test';
/**
* #link http://php.net/manual/en/filter.constants.php reuse the filter constants
*/
function superglobalValue($key, $input = null) {
if ($input === INPUT_POST)
$X = &$_POST;
else
$X = &$_GET;
return (isset($X[$key]) ? $X[$key] : false);
}
function getArrayValue(&$array, $key) {
return (array_key_exists($key, $array) ? $array[$key] : false);
}
//test dump
var_dump(
superglobalValue('test', INPUT_GET),
superglobalValue('test', INPUT_POST),
getArrayValue($_GET, 'test'),
getArrayValue($_POST, 'test')
);
$_GET, $_POST and $_REQUEST dont have any null values by default, only string or array. So I used isset there instead of array_key_exists.
Param order: I always put required params before optional when I can, and the data objects before the manipulation/subjective params. Thats why key is first param for superglobalValue and second param for getArrayValue.
I'm not quite sure what you're trying to achieve, but you could have a look at the __callStatic magic method
class example{
protected static $supers = array('GET', 'POST', 'SERVER', 'COOKIE');
public static function __callStatic($functionName, $arguments){
$index = arguments[0];
$desiredSuper = strtoupper($functionName);
if(in_array($desiredSuper, self::$supers)){
doStuff ( $_{$desiredSuper}[$index] );
}
else{
throw new Exception("$desiredSupper is not an allowed superGlobal");
}
}
}
you could then do:
example::get('id'); //wo do stuff to $_GET['id']
example::server('REQUEST_METHOD'); //Will do stuff to $_SERVER['REQUEST_METHOD']
example::foo('bar'); //throws Exception: 'FOO is not an allowed superGlobal'
Php manual on magic methods: http://ca.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods
Edit
I just noticed your edit, you could try:
$X = {$X};
You can use $_REQUEST["var"] instead of $_GET["var"] or $_POST["var"].
A more complicated way would be to test if the variable exists in the GET array, if it doesnt then its POST. If it does its GET.
$var = null;
if (isset($_GET["varname"]))
{
$var = $_GET["varname"];
}
else
{
$var = $_POST["varname"];
}
If you want a variable to be accessible globally, you can add it tot he $GLOBALS array.
$GLOBALS['test']='test';
Now you can fetch $GLOBALS['test'] anywhere.