...

View Full Version : The "require" command and what the heck?



Fumigator
06-20-2006, 07:19 AM
I'm struggling with something concerning "require".

If I have code like this, with the "displaySQLerror()" function inside the included file "sqlerr.inc":


<?php
require "sqlerr.inc";

function func1() {
...
...
...
}

function func2() {
...
if (!result) {
displaySQLerror();
}
}


Then it all works fine. But, if I put the "require" statement after the functions in the main file, like this:


<?php

function func1() {
...
...
...
}

function func2() {
...
if (!result) {
displaySQLerror();
}
}

require "sqlerr.inc";



I get a "call to undefined function displaysqlerror" error. In fact, I changed the require statement to try to bring in a file that doesn't exist and I didn't get an error! So obviously, somewhere along the line, something's going wrong. Or is it that you need to put require statements up top? That makes no sense.

lavinpj1
06-20-2006, 08:54 AM
Or is it that you need to put require statements up top? That makes no sense.

That makes perfect sense. PHP is executed line by line, from top to bottom, as with most programming languages. It only knows the file is required, when it gets to the require line. If you get to a function in the required file, before you tell it to require the file, you will not have the fuction availiable. That is exactly the same as complaining that this doesn't work...


<?php
echo $x;
$x = 'hello';
?>


I don't really understand how you can confuse the simple structure we know and love, but still, education is good ;)

~Phil~

Fumigator
06-20-2006, 05:19 PM
Alright... hearing you explain it, I get it. I got caught up thinking the "require" code is expanded during parsing rather than during execution, even though I read www.php.net's explanation of include and require 3 or 4 times. It's my paradigm; I'm an ex COBOL programmer and that's how copybooks work... my past sometimes bites me in the arse :p



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum