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;
Related
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
I've been working with Php for less than 2 months (this is also my first question so please tell me if I'm missing something) and it has been going smooth right up till today. I'm working on a form plugin for Wordpress and currently implementing the code to make the forms saved in the database to connect with a shortcode which includes the ID of the form in the database. The 1st form has an ID of 1 and the shortcode is IForm_1. Pretty simple.
The problem occurs when looping thru all the forms and not being able to pass the $ID value from the loop to the IForm function.
$ID= 0;
$FormID= 0;
settype($ID, "integer");
for ($x = 1; $x <= 300; $x++) {
global $ID;
$ID++;
$ShortCode = "IForm_";
$ShortCode .= $ID;
$FormID = $ID;
add_shortcode( $ShortCode, 'IForm_Array' );
$ShortCode ='';
}
here is the loop which is very simple, when the $ShortCode lines up with the shortcode used on the site it works and the IForm get used as it should.
function IForm(){
global $ID;
//testing_decode();
// Gets the value of baseTest from getDB and puts it in test.
$DBForm = getDB($ID);
$Form = $DBForm;
$Form .= "Works but not really";
return $Form;
}
Here is the function.
Problem is that $ID is always 300 in the function which is the end of the loop. IForm is executed when the $ID in the loop lines up with the shortcode ID on the site/post which tells me the $ID value is indeed correct for some part of the loop. When the ID is indeed correct I would like to pass it to the IForm function to use it to find the right form in the database(MySQL).
Now my question is how would I pass (if that can even be done) the $ID value on the 3rd row of the loop to the 5th row of function. Alternatively would be to force break the loop when it lines up and use the last $ID value to be passed to IForm.
WordPress makes this a little more complicated than it needs to be, because you can't pass additional parameters to a shortcode (afaik).
Before we start, let's understand the 300. The loop in which you add the shortcodes gets executed during an early stage of the page load. The actual call to your shortcode function at a later stage. At that time the global $ID variable will have its final value (300 in your case)
Here are two ways to solve this:
First, you can use closures, and inherit $ID from the parent scope:
for ($x = 1; $x <= 300; $x++) {
$ID++;
$ShortCode = "IForm_";
$ShortCode .= $ID;
$FormID = $ID;
add_shortcode( $ShortCode, function () use ($ID) {
$DBForm = getDB($ID);
$Form = $DBForm;
$Form .= "Works but not really";
return $Form;
} );
$ShortCode ='';
}
You can read more about it in the manual. It also explains the difference between use and global variables.
Second, you can use shortcode attributes. You would not use [Form_1] anymore, but [Form id=1]. Then you can access the id within the array that Wordpress automatically passes to your function.
function IForm($attr){
$ID = intval($attr['id']); // A little sanitation, because $attr could come from a user with low privileges
$DBForm = getDB($ID);
$Form = $DBForm;
$Form .= "Works but not really";
return $Form;
}
A little documentation about this is available here.
Lets see what you did there
$ID= 0;
// Define a variable called ID
for ($x = 1; $x <= 300; $x++) {
global $ID;
// get access to global variable id
$ID++;
// increment local or global counter, undefined behaviour
instead i recommend doing
global $ID;
for ($x = 1; $x <= 300; $x++) {
$ID++;
// Do what you think you have to do
do not pass variables over global variables into functions, instead use parameter
function IForm($id){
//testing_decode();
$DBForm = getDB($id);
$Form = $DBForm;
$Form .= "Works very good";
return $Form;
}
and call the function like
IForm(42); //or
IForm($ID);
<?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.
So here is my case:
I have three functions performing some chemical reactions(synthesis1(), synthesis2() & synthesis3() ).
All of these functions will give an answer or a fail in the results.
They were originally separate scripts but are now in a class.
NB: the functions work fine by themselves, even in the class.
Below is my script to instantiate the class and start the functions.
My problem is that since i am running a reaction which fires all the functions;
i get one 1 correct answer and two fails or three fail at once.
What is the best way to handle the situation.
I want one correct answer and suppress the two fails or just show one fail in case of three fails(all fails). I don't expect three right answers.
P.s. All answers are strings.
<?php
// create an object for class name
$aaa = new synthesis();
$abc = new synthesis();
$abcd = new synthesis();
// call the functions in the class
$synthesis1 = $aaa->synthesis1();
$synthesis2 = $abc->synthesis2();
$synthesis3 = $abcd->synthesis3();
// call the if functions
$searches = array($synthesis1, $synthesis2, $synthesis3);
foreach($searches as $search) {
if ($aaa->synthesis1($search)){
echo 'Match found: ' . $search;
break;
}
elseif ($abc->synthesis2($search)){
echo 'Match found: ' . $search;
break;
}
elseif ($abcd->synthesis3($search)){
echo 'Match found: ' . $search;
break;
}
else{ echo"Please try again or try another reaction";}
}
?>
I don't know why you need to instantiate three different objects if you have three individually named methods.
I would think you might want to add a method to your class to simply run all synthesis methods all at once and return the result. So something like:
class synthesis {
protected $synthesis_methods = array(
'synthesis1',
'synthesis2',
'synthesis3',
// add more methods here if needed
}
public function synthesis1() {
// your method logic here
}
public function synthesis2() {
// your method logic here
}
public function synthesis2() {
// your method logic here
}
public function synthesize_all() {
$result = false;
$i = 0;
while(false === $result && $i < count($this->synthesis_methods)) {
$result = call_user_func(array($this, $this->synthesis_methods[$i]));
$i++;
}
return $result;
}
}
You would then only instantiate a single object. Usage would be:
$synth_obj = new synthesis();
var_dump($synth_obj->synthesize_all());
An easy way to handle this is to use OR logic:
if($aaa->synthesis1($search) or $abc->synthesis2($search) or $abcd->synthesis3($search))
{
echo "Match Found: $search";
break;
}
else
{
echo "Please try again or try another reaction.";
}
Seems like this would be pretty simple, however, I'm running into an issue:
Here's the code:
function getValidCustomers() {
global $db;
$getCustomers = $db->GetAll("SELECT * from customers where CustomerActive='1' AND protected IS NULL or protected=0;");
foreach($getCustomers as $customer) {
echo $customer['CustomerID']."\n";
}
}
function updateValidCustomers() {
$customers = getValidCustomers();
for ($i = 0; $i < sizeof($customers); $i++) {
echo "DEBUG: $customers[$i]\n";
}
}
updateValidCustomers();
Basically, the output right now is a list of the CustomerIDs (from updateValidCustomers()). I just want updateValidCustomers() to get the data from getValidCustomers() and then loop through it, so that I can run another query on it that will actually manipulate the database.
Any ideas?
getValidCustomers doesn't return anything, maybe you mean this:
function getValidCustomers() {
global $db;
$getCustomers = $db->GetAll("SELECT * from customers where CustomerActive='1' AND protected IS NULL or protected=0;");
foreach($getCustomers as $customer) {
echo $customer['CustomerID']."\n";
}
return $getCustomers;
}
getValidCustomers() doesn't return anything - it just echoes
Add return $getCustomers to the end of getValidCustomers()
Add return $getCustomers; to getValidCustomers() :D