PHP PDO调用公共方法从其他类的不同类
问题描述:
我想弄明白,我如何可以在另一个类的类中使用公共方法。我得到这个错误PHP PDO调用公共方法从其他类的不同类
Fatal error: Uncaught Error: Using $this when not in object context
我有主类用户,其中包含插入方法,基本上这种方法插入值到数据库。
<?php
class User{
protected $pdo;
public function __construct($pdo){
$this->pdo = $pdo;
}
public function insert($table, $fields){
//here we insert the values into database
}
}
?>
这里是我的config.php文件实例化类,所以我可以用它们
<?php
session_start();
include 'database/connection.php';
include 'classes/user.php';
include 'classes/follow.php';
include 'classes/message.php';
global $pdo;
$userObj = new User($pdo);
$followObj = new Follow($pdo);
$messageObj = new Message($pdo);
?>
,我有其他类的消息,并遵循。在后续类我可以访问用户类的所有方法,并在消息类我试图使用插入方法,它在用户类
<?php
class Message extends User{
public function __construct($pdo){
$this->pdo = $pdo;
}
public static function sendNotification($user_id, $followerID, $type){
//calling this method from user class
$this->insert('notifications', array('By' => $user_id, 'To' => $followerID, 'type' => $type));
}
}
?>
在后续类我想要使用sendNotification的方法,记住这个方法在邮件类,并使用它的方法,从用户类
<?php
class Follow extends User{
public function __construct($pdo){
$this->pdo = $pdo;
}
public function follow($user_id, $followerID){
//here will be query to insert follow in database
//now i need to sendNotification method from user
Message::sendNotification($user_id, $followerID, 'follow');
}
}
?>
获取致命错误
Fatal error: Uncaught Error: Using $this when not in object context
我应该怎么办?
答
使sendNotification
成为非静态函数。删除static
关键字
当方法不依赖于实例化的类时使用静态方法。因此,为什么$this
不能使用
在后续功能的原因,而是执行此
$message = new Message($this->pdo);//pass database connection
$message->sendNotification();//pass the variables
答
您正尝试此方法访问$这从一个静态方法:
public static function sendNotification($user_id, $followerID, $type){
//calling this method from user class
$this->insert('notifications', array('By' => $user_id, 'To' => $followerID, 'type' => $type));
您可以sendNotification的非静态,并创建消息的一个实例,这样你就可以访问用户的公共成员
你不能在静态方法 – Thielicious
由于您使用OOP原理用'$ this',不使用全局关键字。这是不好的做法 – Akintunde007
比方说,我删除了静态关键字,那么我如何才能访问类中的方法? – dinho