在PHP中回显函数变量

时间:2015-05-19 03:56:55

标签: php

我试图在PHP的echo中使用我的函数中的变量来表示一个表单。这是一个更新表单,所以我想显示当前用户信息。

我的功能是这样的:

public static function current()
{
    $id = null;
    if ( !empty($_GET['id'])) {
        $id = $_REQUEST['id'];
    }
    $pdo = Database::connect();
    $sql = "SELECT * FROM customer where counter = ?";
    $q = $pdo->prepare($sql);
    $q->execute(array($id));
    $data = $q->fetch(PDO::FETCH_ASSOC);
    $firstname = $data['firstname'];
    $lastname = $data['lastname'];
    $email = $data['email'];
    Database::disconnect();
}

我的表单试图在值中回显它:

<input class="form-control" name="firstname" id="firstname" 
value="<?php echo !empty($firstname)?$firstname:'';?>">

我似乎无法获得$ firstname变量来回显用户的名字。用户由URL中的字符串调用,该字符串使用?id =

1 个答案:

答案 0 :(得分:3)

两个选项,

return函数所需的值(或值)

public static function current()
{
    $id = null;
    if ( !empty($_GET['id'])) {
        $id = $_REQUEST['id'];
    }
    $pdo = Database::connect();
    $sql = "SELECT * FROM customer where counter = ?";
    $q = $pdo->prepare($sql);
    $q->execute(array($id));
    $data = $q->fetch(PDO::FETCH_ASSOC);
    Database::disconnect();
    return array_intersect_key($data, array_flip(array('firstname', 'lastname', 'email')));
}

...

$user = Thing::current();
echo $user['email'];

或者在类中设置一个静态变量,以便在

之后引用
public static function current()
{
    $id = null;
    if ( !empty($_GET['id'])) {
        $id = $_REQUEST['id'];
    }
    $pdo = Database::connect();
    $sql = "SELECT * FROM customer where counter = ?";
    $q = $pdo->prepare($sql);
    $q->execute(array($id));
    $data = $q->fetch(PDO::FETCH_ASSOC);
    self::$firstname = $data['firstname'];
    self::$lastname = $data['lastname'];
    self::$email = $data['email'];
    Database::disconnect();
}

...

echo Thing::$firstname;

我更喜欢第一件事,但不是返回带有详细信息的数组,而是将其变成Customer对象。