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'];
?>
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
<?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.
I am having a problem with this variable "admin_user_id".. i want to set the val of the var in one function and use that var value in other function here..
But problem is that it gives null. i think its bcz of diff reference of the class..
class ChangeRequestProcessController extends AppController{
static $admin_user_id;
public function ajax_list_of_change_request(){
$this->autoRender = false;
$params = array();
$params[] = $this->Auth->user('id');
//debug($params);
$result = $this->AppProcess->callProcedure('ListOfChangeRequestProcess', $params);
//echo("here:"+$result);
$admin_user_id=$params[0];
//debug( $this->admin_user_id);
echo json_encode($result);
}
public function application_attachment_upload_with_title() {
$this->autoRender = FALSE;
$attachment_array[]=$this->admin_user_id;///p_admin_user_id
//$attachment_array[]="name";///p_uploaded_by
$attachment_array[]=$_POST['title'];///p_attachment_title
// $attachment_array[] = $loged_on_id;
//$attachment_array[] = $_FILES[0]['name'];
//$attachment_array[] = $_POST['title'];
debug($attachment_array);
$result = $application->AttachmentTemp->callProcedure('ChangeRequestAttachmentFinalAddWithTitle', $attachment_array);///call procedure
echo json_encode($result);///result
}
how to solve this problem in php so that the value persists(i think static var will solve it..but it also gives undefined var error inside function)???
Thanks in advance
(this doesn't fit the comment box, so here i go...)
Assuming
// your code to get this...
$admin_user_id = $params[0];
You can store it in a session using this:
if(!session_id()){
session_start();
}
$_SESSION['admin_user_id'] = $admin_user_id; // again, assuming this is the value!
To read it (in your second call/method), simply do:
if(!session_id()){
session_start();
}
$admin_user_id = $_SESSION['admin_user_id'];
For more info, see the php.net: sessions and $_SESSION
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;
I am trying to pull global variable $nsfw but it shows nothing at all. If I echo it inside function, it works. But outside, it fails even when defined as global. Kindly help me out here.
<?php
if(!function_exists('do_example_work'))
{
function do_example_work()
{
global $nsfw;
include("includes/dbconnect.php");
// Create connection
$conn = new mysqli($DBHOST, $DBUSER, $DBPASS, $DBNAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT fieldname FROM table WHERE name='$anything'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if ($row["fieldname"] == 1) {
// do somethin
$nsfw = 25;
exit();
} else {
echo "enjoy";
}
}
} else {
echo "0 results";
}
}
echo $nsfw;
};
?>
There are arguments for and against Globals. You can search Stack and the internet and read about:
Globals are bad in many ways, and should be avoided where possible
Globals are not bad, and can be fine/safe to use if you know what you are
doing
The manual:
http://php.net/manual/en/functions.user-defined.php
You seem to be over complicating things with this basic user defined function.
OUT
If you want to get data out of a function, just use the return statement
function do_example_work() {
// Do some stuff here
$nsfw = 25;
return $nsfw; // Return where needed, in conditional statement or end of function
}
// Will echo "25"
echo do_example_work();
IN
FYI:
To get data into the function from outside, just pass the data into your function from the outside as an argument:
function do_example_work($nsfw) {
/** The var "$nsfw" will have whatever data you pass in through the function call
* You can use it as required - check if $nsfw == something
* Or it might be database login details (urgh)
*/
echo $nsfw." - And words from in the function";
}
// Will echo "Pass in argument - And words from in the function"
do_example_work("Pass in argument");
The keyword global in front of a variable name means that the variable is defined somewhere outside the function, and now I want to use that variable. It does not generate a global variable. So you need to define the variable outside the function, and then you can use that variable inside a function using the global keyword in front of it.
In your code I cannot see you defining the variable outside the function. You are just echoing it out at the bottom of your code.
Any specific reason for keeping global variable inside method ?? Move it outside method and it should work for u.
Or
Try GLOBALS as shown below.
function doit() { $GLOBALS['val'] = 'bar'; } doit(); echo $val;
Gives the output as :
bar
Or
<?php
foo();
bar();
function foo() { global $jabberwocky; $jabberwocky="test data<br>"; bar(); } function bar() { global $jabberwocky; echo $jabberwocky; } ?>