how can i make a function see a variable outside it - php

How can I place a variable inside a function when it is run in order to preg_match the right information. Here is my existing code:
$username = "test";
function is_txt($file) {
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9]{2}_'.$username.'.tar.gz/', $file) > 0;
}
What I am attempting to do is pull the $username variable from outside the function and allow it to be seen within it so I can pull the right matches in my while loop. While the previous comes back blank, if i do the following it works:
$username = "test";
function is_txt($file) {
$username = "test";
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9]{2}_'.$username.'.tar.gz/', $file) > 0;
}

Modify the function to take the $username variable as a parameter:
function is_txt($file, $u) {
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9]{2}_'.$u.'.tar.gz/', $file) > 0;
}
Then call it like:
$username = "test";
is_txt($file, $username);
Alternatively, you can use the global keyword to make the variable visible from the function. This is sometimes useful, but shouldn't be used all over the place. See the variable scope manual entry for more info.

You need to import the var with global:
function is_txt($file) {
global $username;
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9] {2}_'.$username.'.tar.gz/', $file) > 0;
}
But passing the value in as a parameter as explained by Jonah is a better solution in most cases.

Related

Php Laravel Pass value of variables to other methods

I'm refactoring all the codes given to me and I saw in the code that the're so many repeated variables that is using with other methods
which is this
$tag_id = json_decode($_POST['tag_id']);
$tag_name = json_decode($_POST['tag_name']);
$pname = json_decode($_POST['pname']);
$icode = json_decode($_POST['icode']);
$bname = json_decode($_POST['bname']);
$client = json_decode($_POST['client']);
$package = json_decode($_POST['package']);
$reference = json_decode($_POST['reference']);
$prodcat = json_decode($_POST['prodcat']);
$physical_array = json_decode($_POST['physical_array']);
$chemical_array = json_decode($_POST['chemical_array']);
$physpec_array = json_decode($_POST['physpec_array']);
$micro_array = json_decode($_POST['micro_array']);
$microspec_array = json_decode($_POST['microspec_array']);
$prod_type = json_decode($_POST['prod_type']);
$create_physical_id_array = json_decode($_POST['create_physical_id_array']);
$create_chemical_id_array = json_decode($_POST['create_chemical_id_array']);
$create_micro_id_array = json_decode($_POST['create_micro_id_array']);
my question is how can i just use put it in one method and i'll just call it to other methods instead of repeating that code.
thank you
You can't call it from other methods. Because the variables defined to that method are local. Instead you can define the variables as member variables of that class and access from any method or even from outside class depending upon the access specifier.
protected $a=2;
public function method1()
{
echo $this->a;
}
public function method2()
{
echo $this->a;
}
Put it in an array
$post_array = [];
foreach($_POST as $key => $value)
{
$post_array[$key] = json_decode($value);
}
return $post_array;
and then call it like this
$post_array['create_micro_id_array'];
Since it appears you are very much aware of the variable names you want to use... I'll suggest PHP Variable variables
To do this, you can loop through your $_POST and process the value while using the key as variable name.
foreach($_POST as $key => $value)
{
$$key = json_decode($value);
}
At the end of the day, these 4 lines would generate all that... However i'm not so sure of how friendly it may appear to someone else looking at the code. Give it a shot.
You may try extract function.
extract($_POST);

PhP Variables inside functions

I'm having troubles with variables inside functions and being able to read them in a index.php. Let's say I have this function (functions.php):
function firstFunction(){
$id = '1234';
secondFunction($id);
}
function secondFunction($idnumber){
if( $idnumber = 1234 ){
$name = "James"; //should say "james".
}
and in the index.php have something like that:
include(functions.php)
<?php
firstFunction();
echo $name;
?>
does anyone know a possible way to do this?, i need to be a able to read from a variable inside a function that is in another function.
Also when calling a function inside a function allow this to read a variable from the first function.
Thanks.
Variables created inside a function are local to it, you can't read their contents outside of it (because all function-local variables get deleted after the function finished running).
The improper way would be to make the $name variable global in the second function.
A better way to do it would be to use function return values: secondFunction returns $name, and firstFunction returns whatever it gets from calling secondFunction($id).
Oh, and by the way, you have another logical error in your secondFunction: Your if test will not behave like you probably intended because you are using a variable value assignment operator (=) instead of comparison (==) which always succeeds returns the assigned value that evaluates to a "true" value in most (but not all) cases.
This is very bad practice - using globals. The answer you need is:
global $name;
You need to put it above the row:
$name = "James"; //should say "james".
You declare $name inside second function, so it only exists there (that is it's "Scope").
To use it's value you need the functions to return it:
function secondFunction($idnumber){
if ( $idnumber == 1234 ){
$name = "James"; //should say "james".
}
else {
$name = "";
}
return $name;
}
function firstFunction(){
$id = 1234;
return secondFunction($id);
}
and in the index.php have something like that:
<?php
include 'functions.php';
$name = firstFunction();
echo $name;
?>
You can't call a variable like that it is out of scope what you need to do is as follows
function firstFunction(){
$id = '1234';
return secondFunction($id);
}
function secondFunction($idnumber){
if( $idnumber == 1234 ){
return "James";
}
}
Then in your index do this
<?php
include(functions.php);
echo firstFunction();
?>
A variable that is out of scope can not be accessed for example if you defined a variable inside a if statement is would only be able to be used in that statement and it is the same with the functions and variables that are inside. Thought I needed to explain my answer more.
Try this...
index.php
<?php
// Includes
include("functions.php");
// Create a variable to store the output of your function
$returned_name = firstFunction();
// Echo the variable
echo "Name: " . $returned_name;
?>
functions.php
<?php
// Function 1
function firstFunction() {
$id = "1234";
return secondFunction($id);
}
// Function 2
function secondFunction($idnumber) {
if ($idnumber == "1234") {
$name = "James";
} else if ($idnumber == "5678") {
$name = "Brian";
}
return $name;
}
?>

Database select function in PHP?

I am trying to create a function in PHP that accepts two arguments, one being the SQL for a mysqli query and the other being the name I would like to be set as the variable name for the resulting array. Here it is so far:
<?php
function dbSelect($sql,$name) {
include "connect.php";
if($results = $db->query($sql)) {
if($results->num_rows) {
while($row = $results->fetch_object()) {
${$name}[] = $row;
}
$results->free();
}
}
return ${$name};
}
Within the referenced connect.php file is this code
$db = new mysqli('127.0.0.1', 'admin', 'PASSWORD', 'DB_NAME');
However it does not seem to work in its current state. I do not get any errors when calling the function "dbSelect($sql, 'test');" however when I try to reference the supposedly created variable (in this case, $test) I get an undefined error.
Any suggestions or tips on how to fix this?
Thanks in advance.
The ${$name} variable you're assigning to has local scope. That is, the variable disappears as this function returns. Using a variable-variable doesn't make that variable global.
I would recommend you just name the array anything inside your function, and then return the array. Then you can assign its return value to your desired variable instead of passing the variable name.
$test = dbSelect($sql);
You could try to declare global ${$name} inside the function to write to a variable of global scope, but IMHO it's not worth it. It's a better habit to avoid writing functions that have weird side effects on global variables. Keep it simple, just return the results.
The variable variable ${$name} has no practical use in this function. The function returns an array with no variable name. You name it when you assign the function return:
$whatEverYouWant = dbSelect('some sql');
function dbSelect($sql) {
include "connect.php";
if($results = $db->query($sql)) {
if($results->num_rows) {
while($row = $results->fetch_object()) {
$array[] = $row;
}
$results->free();
return $array;
}
}
return false;
}
Return false or maybe an empty array() if there are no results or an error.

How to get a strings data from a different function?

I have a php file with different functions in it. I need to get data from strings in a function, but the strings have been specified in a different function. How can this be done please?
... To clarify, I have two functions.
function a($request) { $username = ...code to get username; }
the username is over retreivable during function a.
function b($request) { }
function b need the username, but cannot retrieve it at the point its called, so need it from function a. I am very much a beginer here (so bear with me please), I tried simply using $username in function b, but that didn't work.
Can you please explain how I can do this more clearly please. There are another 5 strings like this, that function b needs from function a so I will need to do this for all the strings.
...Code:
<?php
class function_passing_variables {
function Settings() {
//function shown just for reference...
$settings = array();
$settings['users_data'] = array( "User Details", "description" );
return $settings;
}
function a( $request ) {
//This is the function that dynamically gets the user's details.
$pparams = array();
if ( !empty( $this->settings['users_details'] ) ) {
$usersdetails = explode( "\n", Tool::RW( $this->settings['users_data'], $request ) );
foreach ( $usersdetails as $chunk ) {
$k = explode( '=', $chunk, 2 );
$kk = trim( $k[0] );
$pparams[$kk] = trim( $k[1] );
}
}
$email=$pparams['data_email'];
$name=$pparams['data_name'];
$username=$pparams['data_username'];
//These variables will retrieve the details
}
function b( $request ) {
//Here is where I need the data from the variables
//$email=$pparams['data_email'];
//$name=$pparams['data_name'];
//$username=$pparams['data_username'];
}
}
?>
#A Smith, let me try to clarify what you mean.
You have several variables, example : $var1, $var2, etc.
You have two function (or more) and need to access that variables.
If that what you mean, so this may will help you :
global $var1,$var2;
function a($params){
global $var1;
$var1 = 1;
}
function b($params){
global $var1,$var2;
if($var1 == 1){
$var2 = 2;
}
}
Just remember to define global whenever you want to access global scope variable accross function. You may READ THIS to make it clear.
EDITED
Now, its clear. Then you can do this :
class function_passing_variables{
// add these lines
var $email = "";
var $name = "";
var $username = "";
// ....
Then in your function a($request) change this :
$email=$pparams['data_email'];
$name=$pparams['data_name'];
$username=$pparams['data_username'];
to :
$this->email=$pparams['data_email'];
$this->name=$pparams['data_name'];
$this->username=$pparams['data_username'];
Now, you can access it in your function b($request) by this :
echo $this->email;
echo $this->name;
echo $this->username;
In the functions where the string has been set:
Global $variable;
$variable = 'string data';
Although you really should be returning the string data to a variable, then passing said variable to the other function.

How do I return a value from a PHP multi-dimensional array using a variable key?

I am having trouble returning a value from a multidimensional array using a key ONLY when I externalize to create a function.
To be specific, the following code will work when inline in a page:
<?php
foreach ($uiStringArray as $key) {
$keyVal = $key['uid'];
if($keyVal == 'global001') echo $key['uiString'];
}
?>
However, if I externalize the code as a function, like so:
function getUIString($myKey) {
// step through the string array and find the key that matches the uid,
// then return uiString
$myString = "-1";
foreach ($uiStringArray as $key) {
$keyVal = $key['uid'];
if($keyVal == 'global001') {
$myString = $key['uiString'];
}
}
return $myString;
}
And then call it like this:
<?php getUIString('global001'); ?>
It always returns -1, and will do so even if I use an explicit key in the function rather than a variable. I can't understand why this works inline, but fails as a function.
I'm a relative PHP noob, so please forgive me if this includes a glaring error on my part, but I've searched all over for discussion of this behavior and found none.
All help appreciated.
i think you need to take a look at PHP's Variable Scope. To problem is that PHP isn't typical of other languages where a variable defined outside of a function is visible within. You need to use something like the $GLOBALS variable or declare the variable global to access it.
To better illustrate, picture the following:
$foo = "bar";
function a(){
// $foo is not visible
echo $foo;
}
function b(){
global $foo; // make $foo visible
echo $foo;
}
function c(){
// acccess foo within the global space
echo $GLOBALS['foo'];
}
The same is basically holding true for your $uiStringArray variable in this scenario.
This is a problem with variable scope, see Brad Christie's answer for more details on variable scope.
As for your example, you need to either pass the array to the function or create it inside the function. Try:
function getUIString($myKey, $uiStringArray = array()) {
// step through the string array and find the key that matches the uid,
// then return uiString
$myString = "-1";
foreach ($uiStringArray as $key) {
$keyVal = $key['uid'];
if($keyVal == 'global001') {
$myString = $key['uiString'];
break;
}
}
return $myString;
}
And call the function using
<?php getUIString('global001', $uiStringArray); ?>
You are having this problem because you are overriding you $mystring variable even if it matches. Send your array as your parameter. It is unknown to your function.You just use break if variable matches
function getUIString($myKey, $uiStringArray=array()) {
// step through the string array and find the key that matches the uid,
// then return uiString
$myString = "-1";
foreach ($uiStringArray as $key) {
$keyVal = $key['uid'];
if($keyVal == 'global001') {
$myString = $key['uiString'];
break;
}
}
return $myString;
}

Categories