这里我想将$ user_id从editdata()函数传递给statusid()函数,但两者都在同一个名为User的类下。
class User{
public function __construct()
{
$this->db=mysqli_connect("localhost","root","","hep1");
}
public function execute_query($db,$query)
{
return mysqli_query($db,$query);
}
public function editdata($user_id)
{
$query="SELECT * FROM employee_form WHERE id='$user_id'";
$kal=$this->execute_query($this->db,$query);
return $kal;
}
public function statusid()
{
self::editdata($user_id); //line 108
$user_id=$user_id; //line 110
$query="SELECT status_name FROM employee_form WHERE id='$user_id'";
$kal=$this->execute_query($this->db,$query);
}
}
但是无论何时运行上面的代码,它都会显示错误,如
注意:未定义的变量:user_id in 第108行的C:\ xampp \ htdocs \ HT \ Tasks \ to-do-using-class \ class.php
注意:未定义的变量:user_id in 第110行的C:\ xampp \ htdocs \ HT \ Tasks \ to-do-using-class \ class.php
请帮助解决这个问题
答案 0 :(得分:0)
您可以按照以下方式使用getter和setter方法。 $ user_id由表单数据设置,或者您可以作为静态传递。
<?php
class User
{
protected $user_id;
public function __construct()
{
$this->db = mysqli_connect("localhost", "root", "", "hep1");
}
public function setUserID($user_id)
{
return $this->user_id = $user_id;
}
public function getUserID()
{
return $this->user_id;
}
public function execute_query($db, $query)
{
return mysqli_query($db, $query);
}
public function editdata($user_id)
{
$query = "SELECT * FROM employee_form WHERE id='$user_id'";
$kal = $this->execute_query($this->db, $query);
return $kal;
}
public function statusid()
{
$user_id = self::getUserID();
self::editdata($user_id); //line 108
$query = "SELECT status_name FROM employee_form WHERE id='$user_id'";
$kal = $this->execute_query($this->db, $query);
}
}
// create a object
$user = new User();
// set user id here when you get
$user_id = '1';
$user->setUserID($user_id);
$user->statusid();
答案 1 :(得分:0)
如果要编写更多或更少的面向对象代码,则应使用面向对象的原则。现在,您的代码看起来像过程代码,但包含在类中。您可以从以下结构开始:
class UserStorage
{
private $db;
// Do not create connection, but instead inject it
public function __construct($db)
{
$this->db = $db;
}
// Use interanl $db, do not pass new connection.
public function query($query)
{
return mysqli_query($this->db, $query);
}
public function fetch($userId)
{
// Consider using prepared statements here.
// Also consider using PDO and not mix procedural and OO style.
return mysqli_fetch_assoc($this->query("SELECT * FROM employee_form WHERE id='$userId'"));
}
}
$db = mysqli_connect("localhost", "root", "", "hep1");
$userStorage = new UserStorage($db);
$userId = 1;
$user = $userStorage->fetch($userId);
$status = $user['status_name'] ?? null;
首先阅读SOLID principles。