我看到类似的问题,但我似乎遇到的问题比基本的问题要多.如何在php中声明变量?我的具体问题是我有一个函数读取数据库表并返回记录(只有一个)作为对象.
class User{
public $uid;
public $name;
public $status;
}
function GetUserInfo($uid)
{
// Query DB
$userObj = new User();
// convert the result into the User object.
var_dump($userObj);
return $userObj;
}
// In another file I call the above function.
....
$newuser = GetUserInfo($uid);
var_dump($newuser);
Run Code Online (Sandbox Code Playgroud)
这里有什么问题,我无法理解.基本上var_dump()在函数中GetUserInfo()工作正常.在var_dump()通话结束后外GetUserInfo()不起作用.
zaf*_*zaf 10
使用PHP5它的工作原理:
<pre>
<?php
class User{
public $uid;
public $name;
public $status;
}
function GetUserInfo($uid)
{
$userObj = new User();
$userObj->uid=$uid;
$userObj->name='zaf';
$userObj->status='guru';
return $userObj;
}
$newuser = GetUserInfo(1);
var_dump($newuser);
?>
</pre>
object(User)#1 (3) {
["uid"]=>
int(1)
["name"]=>
string(3) "zaf"
["status"]=>
string(4) "guru"
}
Run Code Online (Sandbox Code Playgroud)
首先创建您的User类的一个新实例。然后使用该实例调用您的函数并提供 $uid 参数,以便您的查询像应有的那样执行。如果您的数据表中有匹配项,您的用户对象将填充数据库结果。
我个人更喜欢使用静态调用,它使您的代码更具可读性和紧凑性。
不同之处:
$userObj = new User();
$user = $userObj->GetUserInfo('your uid');
Run Code Online (Sandbox Code Playgroud)
或者
$user = User::GetUserInfo('your uid');
Run Code Online (Sandbox Code Playgroud)
我}在第 4 行看到一个奇怪的地方。如果我错了,请纠正我,但我认为它应该在}from the function之后GetUserInfo($uid)。