2017-09-22 31 views
0

最近我检查了SwiftMailer包,发现了这个问题,我无法解释:比索构造和链接

// #1 
$message = new Swift_Message($subject)->setFrom($f)->setTo($t)->setBody($body); 

// #2 
$message = new Swift_Message($subject); 
$message->setFrom($f)->setTo($t)->setBody($body); 

// #3 
$message = new Swift_Message($subject); 
$message->setFrom($f); 
$message->setTo($t); 
$message->setBody($body); 

变#1是从SwiftMailer文档,并不起作用,它提供了一个“意外“ >'“解析错误。这个问题很容易解决,变种#2和#3完美工作。

我认为方法链接是PHP中广泛使用的技术,我也认为#1是完全有效的。为什么它不按预期工作?

我的PHP是V7.1.1

Thx,Armin。

+2

将它更改为这个'(new Swift_Message($ subject)) - > setFrom($ f) - > setTo($ t) - > setBody($ body);' –

+1

您获得了#1的哪些文档?我查看了https://swiftmailer.symfony.com/docs/introduction.html,它显示了@SahilGulati使用的语法。 – Barmar

+0

案例#1从来没有有效的语法。我怀疑你在SwiftMailer的文档中找到它。 – axiac

回答

1

第一个例子不是这样写在文档中,也没有一个类实例化的例子方法链,因为它从来没有有效的PHP。

的文档,而不是被写为这样:

// Create the message 
$message = (new Swift_Message()) 

    // Give the message a subject 
    ->setSubject('Your subject') 

    // Set the From address with an associative array 
    ->setFrom(['[email protected]' => 'John Doe']) 

    // Set the To addresses with an associative array (setTo/setCc/setBcc) 
    ->setTo(['[email protected]', '[email protected]' => 'A name']) 

    // Give it a body 
    ->setBody('Here is the message itself') 

    // And optionally an alternative body 
    ->addPart('<q>Here is the message itself</q>', 'text/html') 

    // Optionally add any attachments 
    ->attach(Swift_Attachment::fromPath('my-document.pdf')); 

注意,类封闭括号内实例化。这允许直接从构造函数中链接方法。

+0

有时候这很容易:-)谢谢!而且“原始”文档也是正确的,我不幸遇到了错误的网页格式副本。 – Nimral