【问题标题】:Extending classes when using autoload使用自动加载时扩展类
【发布时间】:2014-06-06 14:53:42
【问题描述】:

我正在使用 PHPMailer,并希望扩展该类,以便我可以预先设置一些值。我已经设置了自动加载,所以在调用它之前我不需要该文件。我不希望实际设置位于 /var/www/classes/myPHPMailer.php 中,因为我有两台配置不同的服务器,因此请在 Git 忽略的另一个文件中找到设置。所以,它看起来像下面这样。

主文件

<?php
function __autoload($class)
{
    if(file_exists('/var/www/classes/'.strtolower($class).'.php'))
        {require_once '/var/www/classes/'.strtolower($class).'.php';}
}

$mailer=new myPHPMailer(true);
//...
$mailer->send();
?>

文件名:/var/www/classes/myPHPMailer.php

<?php
require_once ('/var/www/private/email.php');
class myPHPMailer extends myPHPMailer_temp {}
?>

文件名:/var/www/private/email.php

<?php
require_once ('/var/www/other_classes/PHPMailer/PHPMailerAutoload.php');
class myPHPMailer_temp extends PHPMailer {
    public function __construct($allow_exceptions=false){
        $this->isSMTP();
        $this->SMTPDebug = 0;
        $this->Host = "smtp.gmail.com";
        $this->Port = 587;
        $this->SMTPSecure = "tls";
        $this->SMTPAuth = true;
        $this->Username = "Username@gmail.com";
        $this->Password = "Password";
    }
}
?>

我收到了Fatal error: Class 'SMTP' not found in /var/www/other_classes/PHPMailer/PHPMailer/class.phpmailer.php on line 1173

如果我require_once /var/www/private/email.php; 并直接唤起myPHPMailer_temp,我不会得到错误。

使用自动加载器时如何扩展此类?另外,我如何查看 PHP 将在哪些目录中搜索?在第 1173 行 ($this-&gt;smtp = new SMTP;) 之前,我希望查看它正在查找的目录,以便进行故障排除。

谢谢

【问题讨论】:

  • 您或许应该考虑使用一致的类命名约定。这是我见过的最奇怪的组合!
  • @Seer。请解释为什么它是悲剧。
  • 它看起来像是混合了各种样式、驼峰式大小写、下划线和一些大写字母。我知道这部分是 PHPMailers 的错误,但我会称它为 TempPhpMailer 之类的东西。只是为了保持一致。 :)

标签: php oop phpmailer autoloader


【解决方案1】:

它失败了,因为 stock PHPMailerAutoload.php 脚本假定它正在加载的类与其自身位于同一文件夹中。

重新定义 __autoload 不是一个好主意(除非您使用的是非常旧的 PHP,您别无选择)因为它往往会破坏依赖于它的东西 - 添加您自己的正确方法类 autoloader 是写一个SPL Autoloader 并将其添加到 autoloader 堆栈中。这就是 PHPMailer 的自动加载器所做的,所以你可以按照这个例子。

在这种情况下,我建议您复制股票自动加载器并将其更改为指向您自己的类文件夹,这或多或少是 @user1032531 建议的。

【讨论】:

    【解决方案2】:

    我不知道为什么用这个替换 function __autoload($class){...} 有效,但它确实有效。任何人都可以提供任何解释,我将不胜感激。

    spl_autoload_register(function ($class) {
        $class=strtolower($class);
        if(file_exists('/var/www/classes/'.$class.'.php'))
            {require_once '/var/www/classes'.DS.$class.'.php';}
    });
    

    【讨论】:

      猜你喜欢
      • 2017-01-20
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多