如何在函数内调用函数

时间:2013-04-30 13:24:46

标签: php function

如何调用函数内的函数?

这是我的function.php

function query_user() {

$q_user = pg_query("SELECT * FROM users WHERE username='".$_SESSION['username']."' AND     password='".$_SESSION['password']."'");

$r_user = pg_fetch_array($q_user, NULL, PGSQL_ASSOC);
$user_tblrows = pg_num_rows($q_user);

if ($user_tblrows==1) {
     $_SESSION['firstname'] = $r_user['firstname'];
     $_SESSION['lastname'] = $r_user['lastname'];

     function welcome_user() {
        echo $_SESSION['lastname'].', '.$_SESSION['firstname'];
    }
 }

在我的单独文件中,我想调用函数welcome_user()

我该怎么做?我很迷惑。我这样做了,我知道这是不正确的。

require 'function.php';
welcome_user();

2 个答案:

答案 0 :(得分:2)

您必须提前声明您的功能,但不能在其他功能中声明。然后在里面调用它:

function welcome_user() {
    echo $_SESSION['lastname'].', '.$_SESSION['firstname'];
}

function query_user() {

$q_user = pg_query("SELECT * FROM users WHERE username='".$_SESSION['username']."' AND     password='".$_SESSION['password']."'");

$r_user = pg_fetch_array($q_user, NULL, PGSQL_ASSOC);
$user_tblrows = pg_num_rows($q_user);

if ($user_tblrows==1) {
     $_SESSION['firstname'] = $r_user['firstname'];
     $_SESSION['lastname'] = $r_user['lastname'];

     welcome_user(); //function call, not definition
 }
}

答案 1 :(得分:0)

你可以这样称呼它;

query_user().welcome_user();