Require return value php

Hello every one

«require_once» and «require» are language constructs and not functions. Therefore they should be written without «()» brackets!

require_once may not work correctly inside repetitive function when storing variable for example:

function foo () require_once( ‘var.php’ );
return $foo ;
>

to make sure variable bar available at each function call , replace require once with require. eg situation : https : //stackoverflow.com/questions/29898199/variables-not-defined-inside-function-on-second-time-at-foreach

function foo () require( ‘var.php’ );
return $foo ;
>

> php check2 . php
result :
bar
bar
bar
bar
bar

There’s been a lot of discussion about the speed differences between using require_once() vs. require().
I was curious myself, so I ran some tests to see what’s faster:
— require_once() vs require()
— using relative_path vs absolute_path

I also included results from strace for the number of stat() system calls. My results and conclusions below.

METHODOLOGY:
————
The script (test.php):
$start_time = microtime ( true );

/*
* Uncomment one at a time and run test below.
* sql_servers.inc only contains define() statements.
*/

//require (‘/www/includes/example.com/code/conf/sql_servers.inc’);
//require (‘../../includes/example.com/code/conf/sql_servers.inc’);
//require_once (‘/www/includes/example.com/code/conf/sql_servers.inc’);
//require_once (‘../../includes/example.com/code/conf/sql_servers.inc’);

$end_time = microtime ( true );

$handle = fopen ( «/tmp/results» , «ab+» );
fwrite ( $handle , ( $end_time — $start_time ) . «\n» );
fclose ( $handle );
?>

The test:
I ran ab on the test.php script with a different require*() uncommented each time:
ab -n 1000 -c 10 www.example.com/test.php

RESULTS:
———
The average time it took to run test.php once:
require(‘absolute_path’): 0.000830569960420
require(‘relative_path’): 0.000829198306664
require_once(‘absolute_path’): 0.000832904849136
require_once(‘relative_path’): 0.000824960252097

The average was computed by eliminating the 100 slowest and 100 fastest times, so a total of 800 (1000 — 200) times were used to compute the average time. This was done to eliminate any unusual spikes or dips.

The question of how many stat() system calls were made can be answered as follows:
— If you run httpd -X and then do an strace -p , you can view the system calls that take place to process the request.
— The most important thing to note is if you run test.php continuously (as the ab test does above), the stat() calls only happen for the first request:

first call to test.php (above):
——————————-
lstat64 («/www», lstat64 («/www/includes», lstat64 («/www/includes/example.com», lstat64 («/www/includes/example.com/code», lstat64 («/www/includes/example.com/code/conf», .
lstat64 («/www/includes/example.com/code/conf/sql_servers.inc», open («/www/includes/example.com/code/conf/sql_servers.inc», O_RDONLY) = 17

subsequent calls to test.php:
——————————
open («/www/includes/example.com/code/conf/sql_servers.inc», O_RDONLY) = 17

— The lack of stat() system calls in the subsequent calls to test.php only happens when test.php is called continusly. If you wait a certain period of time (about 1 minute or so), the stat() calls will happen again.
— This indicates that either the OS (Ubuntu Linux in my case), or Apache is «caching» or knows the results of the previous stat() calls, so it doesn’t bother repeating them.
— When using absolute_path there are fewer stat() system calls.
— When using relative_path there are more stat() system calls because it has to start stat()ing from the current directory back up to / and then to the include/ directory.

Читайте также:  PHP File Upload Example - Tutsmake.com

CONCLUSIONS:
————
— Try to use absolute_path when calling require*().
— The time difference between require_once() vs. require() is so tiny, it’s almost always insignificant in terms of performance. The one exception is if you have a very large application that has hundreds of require*() calls.
— When using APC opcode caching, the speed difference between the two is completely irrelevant.
— Use an opcode cache, like APC!

Konstantin Rozinov
krozinov [at] gmail

Источник

Why I cannot get the return value of require_once function in PHP?

UPDATE: File structure seems to be the following (this is a project I am only working on, I am not the original developer): controller loads (include_once) a file X outside the CodeIgniter app folder structure (the CI app is the admin part of a larger site). file X include_once file controller loads the view this is pretty much it. I can see there is only one entry point (the main index.php file) and that’s the base file ( ).

Why I cannot get the return value of require_once function in PHP?

I already know that include_once would return true or false based on including that file. I’ve read a question on Stackoverflow about using require_once to return your value and print it out.

The problem is that I have an existing project in hand, and inside of that file they return an array. I want to get the output of require_once to see what result I’ve got, but I get 1 instead of array that contains data:

return array('data'=>$result_data,'error'=>null); 
$ret = require_once $this->app->config('eshopBaseDir')."fax/archive.php"; print_r($ret); 

Is there any workaround for this?

This indicated that the file has already been included at that point.

require_once will return boolean true if the file has already been included.

To check you can change to simply require:

$ret = require $this->app->config('eshopBaseDir')."fax/archive.php"; print_r($ret); 
//test.php return array('this'=>'works the first time'); //index.php $ret = require_once 'test.php'; var_dump($ret);//array $ret2 = require_once 'test.php'; var_dump($ret2);//bool true 

Why I cannot get the return value of require_once function in PHP?, You’ll need to run your own tests, but returning from a require is such a marginal feature that it wouldn’t surprise me if it doesn’t support

Variable scope: require_once doesn’t load my variable, but require does

I know this is something silly, but I can’t figure it out. I found a few similar questions all in the context of an MVC framework. That’s my case as well, as I am using CodeIgniter.

I have a file questions.php (that’s included in a view):

require_once '../site_init.php'; var_dump($siteVars); // shows null and a Notice: Undefined variable: siteVars // but the ABSPATH constant is showing as defined! var_dump(ABSPATH); // shows string 'c:\wamp\www\sitename' require '../site_init.php'; var_dump($siteVars); // correctly dumps the content of siteVars array 

and a file site_init.php that should be included everywhere as it holds my site-wide configuration values:

if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); /** Site-wide sitevars */ $siteVars = array(); // set to true in develop environment $siteVars['debug'] == false; 

I know that The require_once statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again however, when I am using require_once , I get a notice saying Undefined variable: siteVars , while using require , all works as expected. However, as you can see in the code above, the constant shows as defined, although they are both defined in the same file. PHP manual: Like superglobals, the scope of a constant is global. You can access constants anywhere in your script without regard to scope.

Читайте также:  Python elasticsearch login password

print_r(get_included_files()); shows site_init.php was included before the require_once, so I shouldn’t have to require(_once) it again.

It must have something to do with variable scope. If I use global $siteVars , it works, without the need to require the file again, but can someone explain exactly why this happens? I am new to CodeIgniter. I can see there is only one entry point (the main index.php file) and that’s the base file ( $_SERVER[‘PHP_SELF’] ).

Ideally, I would also like to know how I can fix this without using global or require .

UPDATE: File structure seems to be the following (this is a project I am only working on, I am not the original developer):

  • controller welcome.php loads (include_once) a file X outside the CodeIgniter app folder structure (the CI app is the admin part of a larger site).
  • file X include_once site_init.php file
  • controller welcome.php loads the view $this->load->view(‘template’, $data);
  • this is pretty much it. Hope this holds the key to a solution.

In CodeIgniter the only variables accessible in a view are passed to it from the controller. There should never be a reason to include anything in this way in COdeIgniter

$d['title'] = 'title'; $this->load->view('main',$d); 

see Config Class http://www.codeigniter.com/user_guide/libraries/config.html for custom config values which could then be accessed in the controller and passed on to the view

This is a logical problem, the scope just helps you see it. Here’s the key to it:

print_r(get_included_files()); shows site_init.php was included before the require_once, so I shouldn’t have to require(_once) it again.

This says that you’ve already included that file before, so require_once() doesn’t do anything when you try it again. It’s not that require_once() «doesn’t load your variable», it just does what it should — avoid including a file that you’ve already loaded.
Obviously, require() doesn’t care for that condition and it re-includes the script and hence imports the said variable in your current scope.

Anyway, including scripts again and again is a horrible method for getting data into your current scope. You should learn how to pass data around using function parameters.

Program stops working after require_once, after the php file is included the var_dump doesn’t give back the required information («data received»). I thought it might have been curl at

Читайте также:  Javascript check css loaded

Require_once not working but not error displayed [duplicate]

I have a problem with require_once. Code:

require_once(__ROOT__.'/_3parties/adodb/adodb-lib.inc.php'); 

When i write the string in url it download me the file, but php doesn’t include it

ini_set('display_errors',1); error_reporting(E_ALL); require_once 'autoloader.php'; echo "2"; define('__ROOT__', dirname(dirname(__FILE__))); require_once(__ROOT__.'/_3parties/adodb/adodb-lib.inc.php'); echo "3"; 

Display only 2, not 3 but any error is displayed. Please help me!

You should use the proper include for adodb:

require_once(__ROOT__.'/_3parties/adodb/adodb.inc.php'); 

In the file you are trying to include, the following line makes sure execution is halted:

ini_set('display_errors',1); error_reporting(E_ALL); require_once 'autoloader.php'; echo "2"; define('__ROOT__', dirname(dirname(__FILE__))); require_once(__ROOT__.'/_3parties/adodb/adodb.inc.php'); echo "3"; 

You are using dirname() twice when setting the ROOT

ini_set('display_errors',1); error_reporting(E_ALL); require_once 'autoloader.php'; echo "2"; define('__ROOT__', dirname(__FILE__)); require_once(__ROOT__.'/_3parties/adodb/adodb-lib.inc.php'); echo "3"; 

Can someone please point out why my require_once() function can’t, This is what is on line 6: require_once(‘private/initialize.php’);. I have tried every version of the file path I can think of and nothing works

Require_once not working to external file

I have a page that I am trying to pull data into from msqsql DB. I got it to work with hep of some folks on this site. I tried to change where the connection variables are tp point to a config file.\, and I don’t even get an error to go off of. I have another file that is using require_once to point to the same config file and it works fine but it’s a much more complicated string. I thought I could just copy the require_once to set this on my page but Im missing something.

Example of my page that works but I don’t want the connection string directly on this page.

 $type = "mixers"; /* create a prepared statement */ if ($stmt = mysqli_prepare($link, "SELECT record_number, Base_Price FROM Products WHERE Unit_Product='u'")) < /* bind parameters for markers */ mysqli_stmt_bind_param($stmt, "s", $type); /* execute query */ mysqli_stmt_execute($stmt); /* bind result variables */ mysqli_stmt_bind_result($stmt, $product, $price); /* fetch value */ while(mysqli_stmt_fetch($stmt)) < $products[$product] = $price; >/* close statement */ mysqli_stmt_close($stmt); > /* close connection */ mysqli_close($link); ?>

Below is Example of my parts page that works with require_once. I tried to copy this entire code and then I’d pair it down later, but I don’t even get an error.

  else < echo 'Invalid catid provided. Return Home try something like '.$_SERVER['PHP_SELF'].'?catid=140'; > function display_category($cat_rn) < require_once('./inc/db_config.php'); require_once('./inc/functions.php'); $con = mysql_connect($catdb['host'],$catdb['user'],$catdb['pass']); if (!is_resource($con)) < die('Could not connect: ' . mysql_error()); >mysql_select_db($catdb['dbname'], $con); 

Any help would be greatly appreciated. I knew to php but I’m learning a lot. -Michael

You’re using require_once() . The scope of that «once» is UNIVERSAL . As soon as you require_once() that file ANYWHERE in your script, all other require_once() for the same file are going to become no-OPS and skip the file:

The above code would print hello only ONCE.

If you want to include/require the file multiple times, then you CAN’T use the _once() variant.

Require_once ignored, ini_set(‘display_errors’, ‘On’); error_reporting(E_ALL);. Now all errors should be visible. Then the best practice (according to me) is to in file that is

Источник

Оцените статью