【问题标题】:PHP function to call another classesPHP函数调用另一个类
【发布时间】:2016-02-08 18:15:25
【问题描述】:

我已经用 PHP 类分隔了几个文件,现在我需要将它们放在一个函数中,如下所示:

include("require-class.php");

require_multi("db-class.php", "settings.php","users-class.php");

class ajaxLogin {
  private $settings;            
  private $users;

  public function __construct(settings $settings, users $users) {
    $this->settings = $settings;
    $this->users = $users;  
  }
}

global $ajaxLogin;
$ajaxLogin = new ajaxLogin;

settings.php 中的类名为 settingsusers-class.php 中的类名为 users。我收到一个错误:

PHP 可捕获的致命错误:参数 1 传递给 ajaxLogin::__construct() 必须是设置的实例,没有给出, 在第 47 行调用 /var/www/html/idcms/admin/class/login-ajax.php 并在线定义在 /var/www/html/idcms/admin/class/login-ajax.php 13、推荐人:http://localhost/idcms/admin/

【问题讨论】:

  • 你是如何调用这个类实例的?

标签: php


【解决方案1】:

ajaxLogin 的构造函数需要两个参数:$settings$user。所以你需要调用:

$ajaxLogin = new ajaxLogin($settings, $user);

当然需要先实例化settingsuser,比如:

$settings = new settings();    // add arguments if required
$user = new user();            // add arguments if required

更新

如果您真的想在您的ajaxLogin 中实例化settingsuser,只需从您的__construct 中删除参数,如下所示:

class ajaxLogin {
    private $settings;          
    private $users;

    public function __construct() {
        $this->settings = new settings();
        $this->users = new users();          
    }
}

但是,第一种方法通常更好,因为使用ajaxLogin 类的每个人都立即知道该类依赖于settingsuser。有关此问题的更详细答案,请参阅this question

【讨论】:

  • 好的,谢谢,我想知道是否有任何方法可以在函数参数中调用它,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多