你能从构造函数返回 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/