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

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;
}

Related

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.

How to check filename in if condition that calls function in php

i'm calling multiple functions from a function...as per my scope i want to call a specific function from parent function as per file that calls that function...
function dispcategories() {
include ('database/connection.php');
$select = mysqli_query($con, "SELECT * FROM categories");
while ($row = mysqli_fetch_assoc($select)) {
echo "<table class='category-table'>";
echo "<tr><td class='main-category' colspan='2'>".$row['category_title']."</td></tr>";
dispsubcategories($row['cat_id']);
dispsubcategoriesstate($row['cat_id']);
echo "</table>";
}
}
From dispcategories i want to call dispsubcategoriesstate() if and only if file updatestate.php calls dispcategories()...if any other file calls dispcategories() than it should not call to dispsubcategoriesstate()...
Hope everyone get the question it is possible to check file name threw if condition or not who calls the function
Including a file is just like typing it into your source code. You can use the magic constant __FILE__ to determine the current file, but this won't tell you what file the calling function was written in.
I'd suggest that you should rather pass a parameter to your function and then call the subroutine based on that.
Declare your function like this and replace the line dispsubcategoriesstate($row['cat_id']); with the block shown below
function dispcategories($fetchSubCategories = false) {
// your code goes here
if ($fetchSubCategories === true) {
dispsubcategoriesstate($row['cat_id']);
}
// the rest of your code goes here
}
When you call it from the file where you do not want sub-categories you will call it like you do now:
dispcategories();
Whenever you want it to fetch the subcategories you can pass the parameter through like this:
dispcategories(true);
I'm using an optional function argument and if this is confusing you should read the manual page.

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

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');

PHP error "Call to undefined function" using simple html dom

I'm fairly new to PHP, and i have a problem in defining a function that returns an array containing a price and description strings.
I am using the "simple html dom" php files that facilitates parsing.
The function i create requires 2 arguments : the link (from which it will grab data) and the id (used to get the proper css syntax).
This is the get_product_details.php
<?
require_once 'simple_html_dom.php';
$priceMatchTable=('span[id=our_price_display]');
$descMatchTable=('div[id=short_description_content]');
function get_prod_details( $link , $id ) {
global $priceMatchTable, $descMatchTable;
$html = file_get_html($link);
$result['price'] = $html->find($priceMatchTable[$id],0);
$result['desc'] = $html->find($descMatchTable[$id],0);
return $result;
}
And this is the main php:
<?php
include 'get_product_details.php';
$link = 'http://micromedia.tn/barette-memoire/1170-barette-m%C3%A9moire-1go-ddr-ii.html';
$id = 0;
$result = get_prod_details($link, $id);
echo $result['price'];
?>
Finally i get an error which tell:
find($priceMatchTable[$id],0); $result['desc'] = $html->find($descMatchTable[$id],0); return $result; }
Fatal error: Call to undefined function get_prod_details() in C:\xampp\htdocs\dom\index.php on line 8
Best regards!
This may sound silliy, but is
include 'get_product_details.php';
really pointing towards "get_product_details.php"?
Disable (//) the function call in you index.php and add a simple echo to your "get_product_details.php" to see if the file gets included.
I think you need something like:
include '/path/from/root_to_your/directory/get_product_details.php';
If your trying this in Windows land, it will look something like:
include 'C:\Documents\something\get_product_details.php';

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.

Categories