PHP variable not passing through to another function sometimes - php

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);

Related

Function that returns a string at contrary

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

PHP: Why is the use of `global` slower than declaring a variable inside a function?

I have been reading PHP manual pages, but I am obviously reading the wrong ones. I ran a few simple tests to see which means of obtaining a variable was faster: using global, declaring the variable inside the function, or using a declared constant.
Summary:
Declaring the variable (e.g., $keyspace = 012...;) was fastest.
Using global (e.g., global $keyspace;).
Defining a constant (e.g., define('keyspace', '01234...'); was slowest.
Question: Why is using global or define slower than declaring a variable in PHP?
(1) Variable defined outside function, function uses global
$keyspace = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
function buildSKU(){
global $keyspace;
$sku = '';
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < 8; ++$i) {
$sku .= $keyspace[random_int(0, $max)];
}
return $sku;
}
(2) Variable defined inside function
function buildSKU(){
$keyspace = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$sku = '';
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < 8; ++$i) {
$sku .= $keyspace[random_int(0, $max)];
}
return $sku;
}
(3) Variable defined as a constant
define('keyspace', '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ');
function buildSKU(){
$sku = '';
$max = mb_strlen(keyspace, '8bit') - 1;
for ($i = 0; $i < 8; ++$i) {
$sku .= keyspace[random_int(0, $max)];
}
return $sku;
}
My test bed:
<?php
$start = microtime(true);
//Put (1) or (2) here...
for($i=0; $i<10000; $i++){ buildSKU(); }
$end = microtime(true) - $start;
echo "\n\nTime: ".$end."\nMemory:".memory_get_peak_usage(true)."\n\n";
Your title is a bit misleading. A function variable is not being 'declared' over and over, it was declared once when you wrote the function code. You also focused on an apples to oranges comparison.
With the function variable example, the scope of the variable is entirely different. A local variable declared inside a function ceases to exist (at least from the scope perspective) once the function completes. It's also being initialized, unlike the global example where the state of the variable at the start of the function is completely unknown.
You spent a lot of time looking at micro optimization and a meaningless benchmark, when the answer is much simpler. It is never better to use the global keyword to inject a variable into function scope.
You have parameters for doing that which can be passed by reference or value, but you did not evaluate those options, although I have to reiterate that in my opinion you aren't really going to find out anything interesting.
In most languages that create a compiled program, function variables are allocated on the stack. Once the function completes, that area of memory is popped off the stack and discarded. PHP however, has a a variable naming and memory allocation scheme that is shared across all variables and objects. You can search for information on 'php zval' and php internals, and find out more about the way variables are allocated, reference counted, and associated with names via symbol tables.
The important point to make here, is that the variable allocation occurs in the same way regardless of the type of variable it is, so any expectation about performance purely of variable allocation syntax is unlikely to provide any meaningful differences.
PHP makes all sorts of decisions in regards to when it needs to make a new zval or simply point multiple symbols at the same one, and that is meant to be transparent to you.
I think the main issue with global is the dependency issue, where your entire code base would be depended on that global variable and its existence, as your code grows , it is very hard to keep track and trouble shoot. Even a name change requires you change everywhere in your code.
in your code if key doesn't change maybe you should consider using constant.
Always use local variable unless it is absolutely needed and there is no other way around.

Static variable in functions

I saw this on W3Schools.
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
The output is 0, 1 and 2.
I wonder why it is not 0, 0 and 0.
Since each time the function is called, the variable x becomes 0 again.
I am a PHP beginner. Thanks!
If you declare a var static inside a function, the var keep it value over multiple calls. You could compare it to a static var inside of classes.
The code you post is a good example to see the actual effect. However I would only carefull use static inside functions, because most of the time, you need the static value somewhere else, reset the value, or something else which requires to much logic and makes the code really bad.
A good example would be a function, which returns a unique identifier for a given identifier. This could be simply achieved by using this code.
function unique_id($id) {
static $count = 0;
return $id . ($id++);
}
This example may clarify. static has a scope, thus is not a global variable. So I can define static $x outside the function and it will be defined there. Since static has scope, it wouldn't make any sense to keep on executing and resetting $x = 0. So, php will only acknowledge it the first time that line is called.
<?php
static $x = 1000;
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>

Use of Anonymous Functions in PHP

This question may be silly. But an anonymous function does not really seem that anonymous to me. Maybe I am understanding it wrong, but an anonymous function must be stored in some variable, so it can later be referenced by this variable. If this is the case, what makes the below function so anonymous or so different than a regular function (other than the ability to store the function itself in a variable)? Or to word it differently, how is an anonymous function MORE useful than a regular function?
<?php
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
function greet($name)
{
printf("Hello %s\r\n", $name);
}
$greet('World');
$greet('PHP');
greet('World');
greet('PHP');
?>
Imagine you want to sort a list of users by username. Instead of defining a named comparison function that you're only going to use once, you can use an anonymous function:
usort($users, function($a, $b) {
return strcmp($a['username'], $b['username']);
});
The function itself has no name, as you show in your example you can still create a "real" function with the "same name". They're usually used like this as callbacks, which may seem more "anonymous":
foo(function ($bar) { ... });
One useful thing about anonymous (or lambda, if you prefer) functions is that they allow for creating your callback function inline with the code that needs it, rather than setting up a global function that will only be used in that one context. For instance:
$foo = native_function($bar, callback_function);
can be instead :
$foo = native_function($bar, function() { return $bar + 1; } );
Another handy thing about anonymous functions is that the variable you set it to calls that function every time, so it's not storing a value, but deriving it instead. This is great if a variable represents some derived value. Example:
$tax = .1;
$total = function() use (&$price, &$tax) { return $price * (1 + $tax); };
$price = 5.00;
echo $total(); // prints 5.50
$price = $price + 1;
echo $total(); // prints 6.60
$discount = $total() - 2;
echo $discount; // prints 4.60;
Instead of having to call a function like get_total and passing it $price every time, you interact with a variable that is always set to the newest value because it derives that value every time with the lambda function.

Factors of a number in an array (PHP function)

I'm probably missing something simple here, but I have this function for finding the factors of a number.
function factor($n){
$factors_array = array();
for ($x = 1; $x <= sqrt(abs($n)); $x++)
{
if ($n % $x == 0)
{
$z = $n/$x;
array_push($factors_array, $x, $z);
}
}
return $factors_array;
}
I then want to do something like this...
factor(120);
print_r($factors_array);
This give me nothing though. Any ideas on where I'm going wrong?
You aren't assigning the variable to the return value of the function. As far as the PHP interpreter is concerned, $factors_array only exists if you're inside the factor() function. Try this:
$factors_array = factor(120);
print_r($factors_array);
Then you can reuse $factors_array in other areas of the code.
Have a look at this page for an explanation of why this happens.
just try this:
print_r(factor(120));
Because you can't access $factors_array; outside the function, this is called scope of variable, usually, variables that defined inside function are not available outside, also, variables that are defined outside function are not available inside function...
Read more Variable scope ¶

Categories