how to include script of variables in a class? undefined variable - php

got a script which has string variables that represent data fields like they are in the database. because this project is a complete mess this is a stage in cleaning it up and not having to rewrite the field name in numerous locations.
so one script 'DataKeys.php' will have variables set to field names.
//results from query1
$keyField1 = 'field1';
$keyField2 = 'field2';
these two vars above is only a snippet of a much longer list.
I want to access this file and use these vars when I am formatting the data to be more friendly for the front end. this script is being accessed in a class however the fields, $keyField1, defined in the script is not being found in the class. I did have the actual string there but I think single access point would be best so when I make future changes I don't need search the whole project.
class DataFormatter {
//put your code here
public function __construct() {
$documentRoot = filter_input(INPUT_SERVER, "DOCUMENT_ROOT");
include ($documentRoot . '/database/values/DataKeys.php');
}
public function cleanData($data){
if (is_null($data) || empty($data))
{
return;
}
foreach($data as $row){
$field1Value = $row[$keyField1];
unset($row[$keyField1]);
}
}
}
I also tried moving the include outside the class definition.
$documentRoot = filter_input(INPUT_SERVER, "DOCUMENT_ROOT");
include ($documentRoot . '/database/values/DataKeys.php');
The error that is being reported is :
Undefined variable: keyField1
SOULTION
Maybe not the optimal way but I took the include statement and placed it inside the function. The code above is just a demo of what I was trying to achieve not the actual code I am using.

the 2 variables are available just after the "include".
you can for example, put the 2 values in properties of the object
include ...;
$this->keyField1 = $keyField1;
$this->keyField2 = $keyField2;

You have to assign DataKeys.php to class member.
class DataFormatter {
private $keyField1;
private $keyField2;
public function __construct($filename) {
include $filename;
$this->keyField1 = $keyField1;
$this->keyField2 = $keyField2;
}
}
$dataFormatter = new DataFormatter(filter_input(INPUT_SERVER, 'DOCUMENT_ROOT') . '/database/values/DataKeys.php');

Related

Is it possible to get the list of the class alias in php as array?

example
namespace Foo;
use Test\One;
use Test\Two;
use Test\Three;
class Sample
{}
How can I get the aliases (USE) as an array?
example of what I am looking to get
$test = [Test\One, Test\Two, Test\Tree];
Does anybody have any suggestions without scanning the file?
or is there a PHP function that will return the list aliases as an array?
Any help will be very appreciated.
Assuming I have the following class and the file is located and named as following file name and location src/Foo.php
namespace Foo;
use Test\One;
use Test\Two;
use Test\Three;
class Sample
{}
now I can scan this file
with this function, I can scan that class and get the result expected.
<?php
use \SplFileObject;
class Scanner
{
public static function getUseAliases()
{
$className = new SplFileObject("src/Foo.php");
$use = [];
while (!$className->eof())
{
$alias = explode("use ", $className->fgets());
if(!empty($alias[1]))
{
$use[] = trim($alias[1]);
}
}
$className = null; //Unset the file to prevent memory leaks
print_r($use);//will print my expected output [Test\One, Test\Two, Test\Three]
}
}
I think there should be a better way to get the same results and this is why I posted my current solution. Please let me know your thoughts.
You can try to use this class:
https://gist.github.com/Zeronights/7b7d90fcf8d4daf9db0c

PHP declared variable, to another file that's included via function

I have some kind of problem, but i don't get it.. I have an function for including/requiring files, which check is file already included and does exists:
function __include($fileclass, $is_required=false) {
static $already_included = array();
// checking is set extension of php file, if not append it.
if (substr($fileclass,-4)!=".php") $fileclass = $fileclass.".php";
// if already included return;
if (isset($already_included[$fileclass])) return true;
// check if file exists:
if (file_exists($fileclass)) {
if (!$is_required) include $fileclass;
else require $fileclass;
$already_included[$fileclass] = 1;
return true;
}
else {
if ($is_required) die("can't find required file");
return false;
}
}
And it works good, but when i started to work on the project, i've used it to include a file, which uses variable from parent file (the one that included it), but it drops notice Notice: Undefined variable: VARIABLE_NAME.
So to be clear at coding:
I have two files file_parent.php and file_child.php, what I've tried:
file_parent.php:
function __include($fileclass, $is_required=false) { /** i've mentioned it above **/ }
class __CONNECTION {
private $test;
public function __construct() {
$this->test = "SOMETHING";
}
};
$Connect = new __CONNECTION();
// here i used it to include the children file:
__include('file_child.php');
file_child.php:
print_r($Connect);
And i get Notice: Undefined variable: Connect.
When i change at file_parent.php my function include:
__include('file_child.php');
to standard include:
include 'file_child.php';
Everything will work fine, variable is defined and will be printed.
I guess there's some problem with function, but could someone explain what's the real reason for happening this, and is there a possible repair to fix it to including/requiring works through function and to not lose variables from previous files.
Thanks!
Well, how do i see, when i printed all defined variables (get_defined_vars()), i got this:
Array
(
[fileclass] => test_file2.php
[is_required] =>
[already_included] => Array
(
)
)
So that means the variables are passed, but only one that exists within function (because the function is temporary), so i could make it work to pass variables to function, but as it's not the only variable I need so I am gonna use one of two way:
global as #Tom Doodler said in comment, and later catch it with $GLOBALS
or use function to do checks and return just a path if exists/or empty string if file doesn't exists and then just include/require it.
Thanks everyone.
I will not accept this answer, so if someone could better explain the way function behaves in this solution, i will accept that.

Replacement variable inside of the replacing variable

I have a function, that check user language and write it down in a variable. After a time, i come of idea to merge they, so that i need a call the function anytime before the first use of a variable, so i put a call of function inside of var, with a idea, that i would be replace it self. But it does not working, becouse it trying to give me a "Closure Object" back, i think it is a function in clear and not the result :( Here is the important part of code:
$GLOBALS['user_language'] = function()
{
return get_user_language();
}
function get_user_language()
{
$user_language = 'en';
$GLOBALS['user_language'] = $user_language;
return $user_language;
}
//somewhere in the script
print_r($GLOBALS['user_language']);
I wish to get 'en' out, nothing more.
function get_user_language()
{
$user_language = 'en';
$GLOBALS['user_language'] = $user_language;
return $user_language;
}
$GLOBALS['user_language'] = get_user_language();
//somewhere in the script
print_r($GLOBALS['user_language']);
But this is strange because you set it already in get_user_language() then you pull it again. It would almost create a loop. The proper way would probably be to remove the $GLOBALS['user_language'] = $user_language; from the function.
Hope this answers your question.
Just use print_r(get_user_language()) instead of print_r($GLOBALS['user_language']);.
If getting the user's language multiple times would be particularly slow (e.g. a database query would be executed over and over again), you can do something like this:
function get_user_language()
{
static $user_language = null;
if ($user_language === null) {
$user_language = 'en'; // this would be where you make the DB query
}
return $user_language;
}
In practice, in a large PHP application, this code would generally be located in a class and would store the value as an object property, so that, for example, the application can cache DB query results for multiple users rather than for only the current one.

PHP repeating piece of code wtih access to variables

How to repeat the same PHP snippet in different PHP files?
For example I define the variable $user, then I insert PHP code, which have an access to this variable.
Update:
I'm going to use this with if statement
Example(without if statement):
function sanitizeString($var)
{
$var = htmlentities($var, ENT_QUOTES, "UTF-8");
return mysql_real_escape_string($var);
}
$user = sanitizeString($_POST['user']);
$pass = sanitizeString($_POST['pass']);
//code i want to repeat in different files
$user=$user;
$pass=$pass;
#salt generation
$salt=uniqid(mt_rand(), true);
#Add data to tables
queryMysql("INSERT INTO accounts VALUES('$user', '".hash('sha512',$pass+$salt)."', '$salt', '$cookie_value')");
mysql_query("INSERT INTO passwordreset VALUES('$user', NULL, NULL)");
//end of code to repeat
Use functions with parameters, that's what they're for. Snippets of code that can be reused in a different context with different variables.
Make classes and methods
class User
{
public $user;
public function User($name)
{
$user = $name;
}
}
$User = new User('name1');
echo $User->user;
$User = new User('name2');
echo $User->user;
$User = new User('name3');
echo $User->user;
$User = new User('name4');
echo $User->user;
Output: name1name2name3name4
U Can add the code or variable in one php file and then include that file where ever u want
U can see the example here
(Removed global keyword as it is not necessary in this case)
One method is to use the $GLOBALS variable, which is accessible anywhere much like $_SERVER, $_POST etc. See Superglobals. As Deceze mentioned, global variables are typically not the best solution, as they are prone to causing accidental errors. For more information about this, give this a read.
$GLOBALS['user'] = "RadGH";
include "my_file.php";
my_file.php:
echo $GLOBALS['user'];
From Bondeye in a comment, using a constant is preferred when dealing with data that does not need to be changed. One of the problems with globals is that somewhere down the line data may be changed or referenced accidentally. Since constants cannot be changed, that is not the case.
define('USER', 'RadGH');
include "my_file.php";
my_file.php:
echo USER;

Can't call an object method. PHP reports variable undefined

This is the weirdest bug! It is probably something silly, but I have no idea how to fix it. If anyone could help, I would be most grateful! I have three files, one is called items.php, another is called tableFunctions.php, and the third is called mysql.php. I use two global objects called 'mysql' and 'tableFunctions'. They are stored in the files 'mysql.php', and
'tableFunctions.php', respectively. In each file, I create an instance of its object, assigning it to the global variable $_mysql, or $_table. like this:
In the file mysql.php:
global $_mysql;
$_mysql = new mysql();
In the file tableFunctions.php:
global $_table;
$_table = new tableFunctions();
Here's how it is supposed to work:
The items.php file includes the tableFunctions.php file...
Which in turn, needs the mysql.php file, so it includes it too.
In the items.php file, I call the method getTable(), which is contained in the object tableFunctions.(and in the variable $_table.) Like this:
$t = $_table->getTable('items');
The getTable function calls the method, arrayFromResult(), which is contained within in the object mysql.(and in the variable $_mysql.) Like this:
$result = $_mysql->arrayFromResult($r);
That's where I get the error. PHP says that the variable '$_mysql' is undefined, but I defined it in the 'mysql.php' file.(see above) I also included mysql.php with the following code:
include_once 'mysql.php';
I have no idea what is wrong! If anyone can help that would be much appreciated.
The source files can be downloaded with the following link: https://www.dropbox.com/sh/bjj2gyjsybym89r/YLxqyNvQdn
That's a common mistake, in the place of definition you need only the line:
$_mysql = new mysql();
and when you want to use it inside a function, only there you have to declare it as a global variable (otherwise it is considered like any other function variable):
global $_mysql;
so, for example, if we'll take your method:
function getTable($tableName) {
$r = mysql_query("SELECT * FROM $tableName");
err($r, 'mysql returned null when getting table!');
$result = $_mysql->arrayFromResult($r);
return $result;
}
it should be changed to:
function getTable($tableName) {
global $_mysql;
$r = mysql_query("SELECT * FROM $tableName");
err($r, 'mysql returned null when getting table!');
$result = $_mysql->arrayFromResult($r);
return $result;
}

Categories