我是相当新的使用PHP类,我已经使用过程方法做了一些PHP一段时间但从未完全在PHP上完成适当的面向对象编程。这让我想到了我的问题:
我有一个名为classes.php的文件,我打算定义所有的php类。在该文件中,我创建了一个类,如下所示:
require_once("connection.php");
class User
{
public function getUserInfo() {
$userinfo = mysqli_query($con,"SELECT * FROM users WHERE username='". $_SESSION['username'] ."'");
while($row = mysqli_fetch_assoc($userinfo)) {
// USER DETAILS:
$userid = $row['id'];
$username = $row['username'];
$userfirstname = $row['first_name'];
$userlastname = $row['last_name'];
$useremail = $row['email'];
$useraddress1 = $row['address_line_1'];
$useraddress2 = $row['address_line_2'];
$userpostcode = $row['postcode'];
$userphone = $row['phone'];
$usermobile = $row['mobile'];
$usercreated = $row['created'];
$usermodified = $row['modified'];
$useraccess = $row['access_level'];
}
}
} // end of User
现在我想在另一个页面中使用该类中定义的变量的值。但是我如何访问这些值呢?
到目前为止,我正在尝试这个(失败):
<?php
include "php_includes/classes.php";
$user = new User();
?>
<div class="somediv">
<?php echo $user->getUserInfo($username) ?>
</div>
我也尝试过:
<?php
include "php_includes/classes.php";
$user = new User();
?>
<div class="somediv">
<?php echo $user->$username ?>
</div>
有没有办法在另一个页面中回显这些变量,以便我可以在例如个人资料页面中使用用户信息?
提前致谢。
答案 0 :(得分:0)
在你的功能之前,你需要制作PUBLIC VARIABLE,如:
public $userid;
然后在函数代码中接下来需要使用:
$this->userid = $row['id'];
修改强>
你的需要是:
class User
{
public $userid;
public function getUserInfo() {
$userinfo = mysqli_query($con,"SELECT * FROM users WHERE username='". $_SESSION['username'] ."'");
while($row = mysqli_fetch_assoc($userinfo)) {
// USER DETAILS:
$this->$userid = $row['id'];
}
}
} // end of User
当你想要显示数据时,你还需要在其他php页面中包含这个类文件。
答案 1 :(得分:0)
您必须将变量声明为 PUBLIC
class User
{
public function getUserInfo() {
$userinfo = mysqli_query($con,"SELECT * FROM users WHERE username='". $_SESSION['username'] ."'");
while($row = mysqli_fetch_assoc($userinfo)) {
// USER DETAILS:
public $userid = $row['id'];
}
}
}
有关详细信息,请查看here
答案 2 :(得分:0)
你应该从函数返回值。
require_once(&#34; connection.php&#34);
a.map(&:amount).sum
#=> 1234
# OR
a.to_a.sum(&:amount)
#=> 1234
现在只需要显示用户的详细信息
class User
{
public function getUserInfo() {
$userinfo = mysqli_query($con,"SELECT * FROM users WHERE username='". $_SESSION['username'] ."'");
$row = mysqli_fetch_assoc($userinfo);
return row
}
}
因此,您可以检查行是否为null,并且此类函数可以返回整个数组,此类包含在该文件中。