Page 1 of 1
problem in objects ??
Posted: Sun May 27, 2007 7:12 am
by PHPycho
Hello forums !!
i had a problem while creating a objects..
i usually create the objects at the top of the index.php page and all other files are included in the index.php page..
suppose i create a object say :
while using this object in the another page say cat.php which is included in the index.php.
Code: Select all
if(isset($_POST['SUBMIT'])){
global $obj1;
$obj1->save();
}
i had to make the object global, other it doesnt work..inside the functions its obvious to make the varible global in order to use it..but i had to use it in each if() condition.....
Any idea avoid this situation of making global in case of if(), while() etc conditions
Awaiting for your great help
Thanks in advance to all of you
Posted: Sun May 27, 2007 7:22 am
by Ambush Commander
PHP does not have a notion of scoping conditional structures, so global inside an if or loop is unnecessary. You will only need global when you're in a function.
Edit: Ah, I misread the question. That's weird.
Posted: Sun May 27, 2007 7:23 am
by volka
is cat.php included within a function, something like
Code: Select all
function xyz() {
include 'cat.php';
}
?
Which php version do you use?
Posted: Sun May 27, 2007 7:33 am
by feyd
I can't make any sort of possible culprit without more code being posted.
Posted: Sun May 27, 2007 10:38 pm
by PHPycho
Ya i included the files using a function.
I used
Code: Select all
if(isset($_GET['page']){
loadPHP($_GET['page']);
}
Code: Select all
loadPHP($page){
include $page.".php";
}
Awaiting for your help.
thanks again
Posted: Sun May 27, 2007 10:41 pm
by Ambush Commander
When a file is included inside a function, it inherits the function's scope, not the global one. So yes, global is necessary.
Posted: Sun May 27, 2007 11:17 pm
by PHPycho
thanks for the help..
I want to know if there is any other method to use functions and not to declare as global..
thanks again..
Posted: Mon May 28, 2007 5:01 am
by volka
You could pass parameters to the function. The included script can access them without marking htme as global.
Posted: Mon May 28, 2007 6:58 am
by Chris Corbyn
PHPycho wrote:thanks for the help..
I want to know if there is any other method to use functions and not to declare as global..
thanks again..
At the top of your loadPHP() function...
Code: Select all
function loadPHP()
{
foreach (array_keys($GLOBALS) as $k)
{
$$k =& $GLOBALS[$k];
}
//continue
}
I'd probably consider that bad programming though. If you're using OOP there's probably a better way to "globalise" your objects. Say for example a registry.
Posted: Wed May 30, 2007 12:29 am
by PHPycho
can i know how you include the pages
ie using function or simply using include|require etc.
thanks a lot