你能从构造器返回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 );这实际上是正确的吗,例如,根据__construct方法的结果,$ftp_sftp变量是否为false或保持类,或者这是完全错误的逻辑吗?
发布于 2013-01-13 01:15:45
不是的。构造函数没有返回值。如果您需要从构造函数获得某种类型的结果,您可以做一些事情:
如果需要返回值,可以使用一个方法来完成繁重的任务(通常称为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-13 01:21:13
构造函数不能返回值。在这种情况下,您可以抛出异常:
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-13 01:21:56
有一个有趣的线索来解释为什么构造函数没有返回值Why do constructors not return values?。
此外,通过返回"False“,您似乎想要否定对象实例化。如果是这种情况,我建议您在连接失败时抛出一个异常,这样对象创建就会失败。
https://stackoverflow.com/questions/14295761
复制相似问题