PHP pass variable by referenced's issue in closure function - php

<?php
/**
* Created by PhpStorm.
* User: james
* Date: 8/30/16
* Time: 12:28 PM
*/
include_once './vendor/autoload.php';
use Workerman\Worker;
use Workerman\Lib\Timer;
$active_socket = [];
$coap_wk = new Worker('Coap://0.0.0.0:50008');
//print_r($coap_wk);
$http_wk = new Worker('http://0.0.0.0:8080');
$http_wk->count = 4;
//
$http_wk->onWorkerStart = function ($worker) use(&$active_socket)
{
//global $active_socket;
//echo "Worker's id ={$worker->id}\n";
//$active_socket = $active_socket;
echo count($active_socket);
if ($worker->id === 3)
{
//$socket = $active_socket;
Timer::add(5, function() use (&$active_socket) {
var_dump(count($active_socket)); //
//echo " 4 eggs, 4 process.\n";
//print_r(count($active_socket));
});
}
};
$http_wk->onMessage = function ($connect, $data) use(&$active_socket)
{
//global $active_socket;
$active_socket[] = $connect;
//var_dump($data);
echo "onmessage";
var_dump($active_socket);
Timer::add(5, function() use (&$active_socket) {
var_dump(count($active_socket));
//echo " 4 eggs, 4 process.\n";
//print_r(count($active_socket));
});
$connect->send(rand(999, 99999999));
};
Worker::runAll();
** Here is my problem:**
I create two callback closure function and pass the same variable by reference.
When I receive request, I will change the variable $active_socket on the second callback function, and var_dump the number of $active array.
According to PHP's manual, if you pass a variable by reference. It means the same memory address, but in onWorkerStart's callback function, I can not get $active_socket's value changed by onMessage.
Does anyone can tell me what happen? Or something I missunderstand PHP's usage of callback function and variable pass by referenced.
Thank you sincerecely.

The key is $http_wk->count = 4; which means there are 4 processes.
The variables between processes are separate.
If $http_wk->count = 1; it will working well.

Related

Can't get $_COOKIE[''] inside PHP function

I have a custom WordPress plugin that I developed.
Inside it I have 2 functions:
<?php
function A (){
B ();
}
function B (){
$result = "XXX" . $_COOKIE['mtc_id'] . "XXX";
return $result;
}
echo $_COOKIE['mtc_id'];
?>
Why is my $_COOKIE['mtc_id'] null in function B () ($result = "XXXXXX") whereas when I echo $_COOKIE['mtc_id'] I get my desired cookie value?
I'm sure it's something very basic but I am missing it. I even tried to define it outside and use the variable inside the function but still in vain.
Of course, my cookie is of same domain and as mentioned, if I echo it, it gives me the required string.
Also, the cookie is already set because function A () is trigered way after the cookie is loaded. I have simplified the code to the maximum.
You did not return the value in your B function
<?php
function A (){
echo B ();
}
function B (){
$result = "XXX" . $_COOKIE['mtc_id'] . "XXX";
//Always remember to return the value;
return $result;
}
echo $_COOKIE['mtc_id'];
?>

PHP variables in function argument is not working

I've retried solving this, by using a condition and a default attribute as recommended.
User-generated data is declared before to $Variable_1:
<?php
$Variable_1 = 'abc123!' //The user inputs the data
if ($booleanvalue == true) { // User selects if they've put data
name($user_data, $Variable_0 = $Variable_1 );
}
//Then the function will use the user's data from $Variable_1
function name($user_data, $Variable_0 = null) {
//Other code...
}
$Variable_2 = name($user_data);
$data['variable_2'] = $Variable_2;
?>
Is it possible to have $Variable_0 pre-declared and then put as an argument?
you have a few mistakes in your code. and I don't think that you can use a function named name.
you could do it this way for example:
<?php
$Variable_1 = 'abc123!';
function test($data) {
global $Variable_1;
//Other calculations...
return $Variable_1 . $data;
}
$testdata = "huhu";
$Variable_2 = test($testdata);
$data['variable_2'] = $Variable_2;
echo $data['variable_2'];
?>
I agree with the comment by El_Vanja, but you can access a global variable through the magic $GLOBALS array anywhere.
<?php
// what you might actually want
function name($variable = 'abc123!')
{
// if no value is passed into the function the default value 'abc123!' is used
}
$variable = 'abc123!';
// what you could do
function name2($variable)
{
// $variable can be any value
// $globalVariable is 'abc123!';
$globalVariable = $GLOBALS['variable'];
}
I'd also like to point out that currently you have no way of controlling what type of data is passed to the function. You might consider adding types.
<?php
<?php
// string means the variable passed to the function has to be a ... well string
function name(string $variable = 'abc123!'): void
{
// void means the function doesn't return any values
}
name(array()); // this throws a TypeError

Parameters to a class constructor function

I'm trying to adapt a class of mine that handles tags for events stored in a JSON file. You can create tags, delete them, restore them, view them, etc. In the code below for this library you can see that I retrieve the array from the file during the constructor function so I use it and manipulate it throughout my classes' functions.
class tagHandler {
private $tagsFile = "/home/thomassm/public_html/functions/php/tags.json";
private $LstTags;
private $LstReturn;
function __construct() {
$this->LstTags = array();
if(!file_exists ($this->tagsFile)){
$fHND = fopen($this->tagsFile, "w");
$tmpArray = array(array("EID","EName","EColor", "EDel"));
fwrite($fHND, json_encode($tmpArray));
fclose($fHND);
}
$encodedInput = file ($this->tagsFile);
$this->LstTags = json_decode($encodedInput[0], true);
if(!$this->LstTags) $this->LstTags = array();
}
function __destruct(){
$this->update();
}
public function update(){
$this->LstTags = array_values($this->LstTags);
$fHND = fopen($this->tagsFile, "w");
fwrite($fHND, json_encode($this->LstTags));
fclose($fHND);
//empty memory region
$this->LstTags = array();
$encodedInput = file ($this->tagsFile);
$this->LstTags = json_decode($encodedInput[0], true);
}
//More functions that use the collected array here.
I am trying to adapt the class to deal with people signed up to my events. Each event has a record in my database that will store a field for an array of males who sign up and females who sign up. I wish for the constructor class to get the arrays(s) from the record so they can be manipulated like the previous class. The issue is to get the array I have to search the DB for a record with the Event ID (EID) and that will require a variable passed to the constructor function. To make things worse, this parameter has to be able to change in a loop. For example, the page listing all the events will have to use this class in a loop going through each record, so it can retrieve the array to manipulate it and then show it in a table / fullcalendar before repeating the process to get the next event. I have put the code I have so far below. Its not complete (some variables haven't been renamed to male and female, etc) and may be completely wrong, but it will give you a base to explain from.
class signupHandler {
private $LstMaleS;
private $LstFemaleS;
private $LstReturn;
function __construct($IntEID) {
$this->LstTags = array();
$StrQuery = "SELECT MaleS, FemaleS FROM tblEvents WHERE EID = ?";
if ($statement = TF_Core::$MySQLi->DB->prepare($StrQuery)) {
$statement->bind_param('s',$IntEID);
$statement->execute ();
$results = $statement->get_result ();
}
$this->LstTags = json_decode($encodedInput[0], true);
if(!$this->LstTags) $this->LstTags = array();
}
Thanks,
Tom
function decodeNames($StrNames){
$this->LstNames = array();
$this->LstNames = json_decode($StrNames, true);
if(!$this->LstNames) $this->LstNames = array();
$this->LstNames = array_values($this->LstNames);
}
function update(){
$this->LstNames = array_values($this->LstNames);
return json_encode($this->LstNames);
}
public function addSignUp($StrNames, $StrUsername, $StrStatus){
$this->decodeNames($StrNames);
$BlnPresent = false;
for($i = 0; $i < count($this->LstNames); $i++){
if($this->LstNames[$i][0] == $StrUsername){
$this->LstNames[$i][1] = $StrStatus;
$BlnPresent = true;
}
}
if($BlnPresent == false){
array_push($this->LstNames, array($StrUsername, $StrStatus, date("Y-m-d H:i:s")));
}
return $this->update();
}
I have decided to pass the encoded JSON array to the class each time I call a function from it. Before every function it is decoded and turned into an array and at the end it is then re-encoded and returned back to the file calling it. Now I no longer have any constructor or destruct functions.

How do I share same variable between independent functions

How do I share same variable between independent functions? I don't want to use globals and at the moment, I'm not using OO. This example only works within nested functions:
$example = function() use ($id){
echo 'id is: ' . $id;
};
Is there a way to access (read: to call) that nested function from a different function? I could then return $id.
Main issue: I'm retrieving an ID from a database and I want the moderator to be able to edit material based on the ID that is being retrieved from the database.
As mentioned in my comment , I'm not 100% what exactly you mean by independent and nested function but here is PHP's manual on (anonymous function)[http://php.net/manual/en/functions.anonymous.php].
Anyway I have put a sample together assuming you are really meaning nested functions
<?php
function wrapperOne($id) {
$newId = function($id) {
return $id * 2;
};
return $newId($id);
}
function wrapperTwo($id) {
$doSomething = function() use(&$id) {
$id *= 3;
};
$doSomething();
return $id;
}
echo wrapperOne(2); // 4;
echo PHP_EOL;
echo wrapperTwo(2); // 6;
You can use passing by reference read this
function changeMyID(&$id)
{
$id = 1;
}
function printMyID($id)
{
echo $id;
}
$id = 2;
changeMyID($id);
printMyID($id); // this will output 1;

How to store the class object array value into database and retrieve theses value from the database

I am working in a class which has dynamic arrays. I need to store the results of these dynamic arrays of the class in the database.
<?php
require_once('ag.php');
class H
{
var $Voltage;
var $Number;
var $Duration;
function H($Voltage=0,$Number=0,$Duration=0)
{
$this->Voltage = $Voltage;
$this->Number = $Number;
$this->Duration = $Duration;
}}
//This will be the crossover function. Is just the average of all properties.
function avg($a,$b) {
return round(($a*2+$b*2)/2);
}
//This will be the mutation function. Just increments the property.
function inc($x)
{
return $x+1*2;
}
//This will be the fitness function. Is just the sum of all properties.
function debug($x)
{
echo "<pre style='border: 1px solid black'>";
print_r($x);
echo '</pre>';
}
//This will be the fitness function. Is just the sum of all properties.
function total($obj)
{
return $obj->Voltage*(-2) + $obj->Number*2 + $obj->Duration*1;
}
$as=array();
for($i=0;$i<$row_count;$i++)
{
$adam = new H($fa1[$i],$fb1[$i],$fcc1[$i]);
$eve = new H($fe1[$i],$ff1[$i],$fg1[$i]);
$eve1 = new H($fi1[$i],$fj1[$i],$fk1[$i]);
$ga = new GA();
echo "Input";
$ga->population = array($adam,$eve,$eve1);
debug($ga->population);
$ga->fitness_function = 'total'; //Uses the 'total' function as fitness function
$ga->num_couples = 5; //4 couples per generation (when possible)
$ga->death_rate = 0; //No kills per generation
$ga->generations = 10; //Executes 100 generations
$ga->crossover_functions = 'avg'; //Uses the 'avg' function as crossover function
$ga->mutation_function = 'inc'; //Uses the 'inc' function as mutation function
$ga->mutation_rate = 20; //10% mutation rate
$ga->evolve(); //Run
echo "BEST SELECTED POPULATION";
debug(GA::select($ga->population,'total',3)); //The best
$as=array((GA::select($ga->population,'total',3))); //The best
}
?>
$as is an array which contains the value I need to store in the database. Kindly help me in that. This $as array contains the values of $adam,$eve,$eve1 after computation.
To store an array in a database you can use the PHP serialize function
$serialized_array = serialize($as); // This can now be stored in the database
Then when you retrieve it from the database use unserialize
$back_to_array = unserialize($result_from_database); //You now have the array again
Also consider using PHP5 notation for class declarations such as declaring function and member variables as public/protected/private and using function __construct() instead of function your_class_name
<?php
//serialize and store the value into the database
//however to storing the object into the db is not good practice
$val = serialize($$as);
$sql = "insert into table_name field_name values('$val')";
//execute the query
$query = mysqli_query($connection_variable, $sql) or die('error in query');
//while retrieving use unserialize($str) function
unserialize($val);

Categories