加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 从__constructor返回false

发布时间:2020-12-13 22:04:56 所属栏目:PHP教程 来源:网络整理
导读:你可以从构造函数中返回false吗? ?phpclass ftp_stfp{ //private vars of the class private $host; private $username; private $password; private $connection_type; private $connection = false; function __contruct( $host,$username,$password,$con
你可以从构造函数中返回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,$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,$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,$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,$connection_type );
}
catch (Exception $e)
{
    // do something
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读