简体   繁体   English

如何在 php 中返回新实例

[英]How to return a new Instance in php

I have the following code:我有以下代码:

class Email_Driver
{
   public function testEmail_Driver()
    {
       echo "testEmail_Driver".RT;
    }
}
    
class Email_Smtp extends Email_Driver
{
    public function testEmail_Smtp()
    {
       echo "testEmail_Smtp".RT;
    }
}

class Email
{
  public $instance;

  public function __construct()
  {
      $this->instance = new Email_Smtp();
      return $this->instance;
  }
}


$mail = new Email();
var_dump($mail);
$mail->testEmail_Smtp();      //Fatal error: Uncaught Error: Call to undefined method Email::testEmail_Smtp()
$mail->testEmail_Driver();

How do I get access to methode testEmail_Smtp() and testEmail_Driver() in this case?在这种情况下,如何访问方法 testEmail_Smtp() 和 testEmail_Driver()?

The code below should be enough.下面的代码应该足够了。 Basically the class Email now acts exactly the same as class Email_Smtp :基本上 class Email现在的行为与 class Email_Smtp

class Email_Driver
{
   public function testEmail_Driver()
    {
       echo "testEmail_Driver".PHP_EOL;
    }
}
    
class Email_Smtp extends Email_Driver
{
    public function testEmail_Smtp()
    {
       echo "testEmail_Smtp".PHP_EOL;
    }
}

class Email extends Email_Smtp 
{
  // any more methods
}

$mail = new Email();
var_dump($mail);
$mail->testEmail_Smtp();      
$mail->testEmail_Driver();

You are assigning subsiduary classes to $instance so in order to make you code work you need to use that instance您正在为$instance分配子类,因此为了使您的代码正常工作,您需要使用该实例

<?php
    define('RT','<br />');
    
    class Email_Driver{
        public function testEmail_Driver(){
            echo "testEmail_Driver".RT;
        }
    }
        
    class Email_Smtp extends Email_Driver{
        public function testEmail_Smtp(){
           echo "testEmail_Smtp".RT;
        }
    }

    class Email{
      public $instance;
      public function __construct(){
          $this->instance = new Email_Smtp();
      }
    }


    $mail = new Email();

    printf('<pre>%s</pre>',print_r($mail,true));
    $mail->instance->testEmail_Smtp();      //Fatal error: Uncaught Error: Call to undefined method Email::testEmail_Smtp()
    $mail->instance->testEmail_Driver();

?>

Which outputs:哪个输出:

Email Object
(
    [instance] => Email_Smtp Object
        (
        )

)
testEmail_Smtp
testEmail_Driver

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM