从__construct返回false

时间:2013-01-12 17:14:12

标签: php

你能从构造函数中返回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 个答案:

答案 0 :(得分:6)

没有。构造函数没有返回值。如果你需要从构造函数中获得某种结果,你可以做一些事情:

如果您需要返回值,请使用方法进行繁重的操作(通常称为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 conntect()
{
    // connection failed
    throw new Exception('connection failed!');
}

try 
{
    $ftp_sftp = new ftp_sftp( $host, $uname, $pword, $connection_type );
}
catch (Exception $e)
{
    // do something
}

答案 1 :(得分:4)

构造函数无法返回值。你可以在这个stuation中抛出异常:

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.
}

答案 2 :(得分:1)

有一个有趣的线程,说明构造函数为什么没有返回值Why do constructors not return values?

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

答案 3 :(得分:1)

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

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

如果连接是公开的。