4

您可以从构造函数返回 false 吗?

<?php


class ftp_stfp{

    //private vars of the class
    private $host;
    private $username;
    private $password;
    private $connection_type;
    private $connection = false;


    function __contruct( $host, $username, $password, $connection_type ){

        //setting the classes vars
        $this->host         = $host;
        $this->username     = $username;
        $this->password     = $password;
        $this->connection_type = $connection_type;

        //now set the connection into this classes connection
        $this->connection = $this->connect();

        //check the connection was set else return false
        if($this->connection === false){
            return false;   
        } 
    } ... etc etc the rest of the class

调用类:

$ftp_sftp = new ftp_sftp( $host, $uname, $pword, $connection_type );

这实际上是否正确,即 $ftp_sftp var 是否为假或根据 __construct 方法的结果持有该类,或者这是完全错误的逻辑?

4

4 回答 4

8

不,构造函数没有返回值。如果您需要从构造函数中获取某种结果,您可以执行以下操作:

如果您需要返回值,请使用一种方法来完成繁重的工作(通常称为init())。

public static function init( $host, $username, $password, $connection_type ){

    //setting the classes vars
    $this->host         = $host;
    $this->username     = $username;
    $this->password     = $password;
    $this->connection_type = $connection_type;

    //now set the connection into this classes connection
    $this->connection = $this->connect();

    //check the connection was set else return false
    if($this->connection === false){
        return false;   
    } 
}

$ftp_sftp = ftp_sftp::init();

将结果存储在成员变量中,并在调用构造函数后检查其值。

function __construct( $host, $username, $password, $connection_type ){

    //setting the classes vars
    $this->host         = $host;
    $this->username     = $username;
    $this->password     = $password;
    $this->connection_type = $connection_type;

    //now set the connection into this classes connection
    $this->connection = $this->connect();
}

$ftp_sftp = new ftp_sftp( $host, $uname, $pword, $connection_type );
if ($ftp_sftp->connection !== false)
{
    // do something
}

您可以让您的connect()方法引发异常。这将立即停止执行并转到您的catch块:

private method contect()
{
    // connection failed
    throw new Exception('connection failed!');
}

try 
{
    $ftp_sftp = new ftp_sftp( $host, $uname, $pword, $connection_type );
}
catch (Exception $e)
{
    // do something
}
于 2013-01-12T17:15:45.450 回答
4

构造函数不能返回值。您可以在这种情况下抛出异常:

if($this->connection === false){
  throw new Exception('Connection can not be established.');  
}

然后您可以在 try-catch 块中实例化变量。

try
{
  $ftp_sftp = new ftp_sftp( $host, $uname, $pword, $connection_type );
}
catch(Exception $e)
{
  //Do whatever you want.
}
于 2013-01-12T17:21:12.790 回答
1

关于为什么构造函数没有返回值有一个有趣的线程为什么构造函数没有返回值?.

此外,通过返回“False”,您似乎想要否定对象实例化。如果是这种情况,我建议您在连接失败时抛出异常,这样对象创建将失败。

于 2013-01-12T17:21:56.333 回答
1

我认为您可以在外部创建一个对象并直接使用您的 connect() 方法并在那里进行测试

$ftp_sftp = new ftp_sftp( $host, $uname, $pword, $connection_type );
$ftp_sftp->connect();

如果连接是公开的。

于 2013-01-12T17:40:12.930 回答