php - 从 __constructor 返回 false

标签 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 方法的结果持有类,或者这是完全错误的逻辑?

最佳答案

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

如果您需要返回值,请使用方法来完成繁重的工作(通常称为 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 block :

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
}

关于php - 从 __constructor 返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14295761/

相关文章:

php - 在连接表中计算结果并在侧边栏中显示 () 之间

php - 这可以作为单个更新查询运行吗?

php - 如何修复这个 SQL 语法错误?

php - Codeigniter 事件记录类错误与 MySQL 原始查询

php - 使用 ajax 进行多项选择

PHP:文本 explode ()问题

php - 使用 Swift 和 PHP 为 iOS 应用制作联系表单

php - 与 XPath 等效的 Mysql like 子句

php - 多个日期的 cakephp 验证

php - 基于 MySQL 查询中的 If Else 语句的自定义 CSS