开发者

using global inside of function to get variable from included file. PHP

Really simple I just think it's me.

this is file 1.php

if(ctype_digit($_GET['id']))
{
    $开发者_StackOverflow中文版item_id = "Hello";
}
else
{
    //Something
}

this is file 2.php

function item_show(){

        $item_query = "SELECT title FROM tbl_items WHERE id='" . mysql_real_escape_string($item_id) . "' ";

}

Now my question is how do I get the value of $item_id from 1.php inside the function in 2.php ?

To add file 1.php and file 2.php are both included in index.php


Is there anything stopping you just passing it as a function argument like this?

item_show($item_id);

or (the very hacky and not recommended):

function item_show(){
        global $item_id;
        $item_query = "SELECT title FROM tbl_items WHERE id='" . mysql_real_escape_string($item_id) . "' ";

}


I suppose index.php includes the files following the order file1.php, file2.php.

In this case, you can use the following code in file2.php:

function item_show() {
  global $item_id;
  $item_query = "SELECT title FROM tbl_items WHERE id='" . mysql_real_escape_string($item_id) . "' ";
}


function item_show($item_id){}

or

function item_show()
{
    global $item_id;
}


  1. Use require to include the code from 1.php.
  2. In 1.php, return the value of $item_id.
  3. Call the function in 1.php from 2.php.


function item_show()
{
    global $item_id;
}

but I heard that using global is not a good coding method.


Use

$GLOBALS['item_id']

in both files, instead of

$item_id
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜