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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- CakePHP:如何使用Form帮助程序同时更新多个记录
- ThinkPHP实例化模型的四种方法概述
- php设计模式 Facade(外观模式)
- php – CodeIgniter会话set-cookie重复 – 如何解决
- PHP Parse Error: syntax error, unexpected $end 错误的解
- PHP编程:PHP实现对站点内容外部链接的过滤方法
- 在beforeAction中渲染视图时,在Yii中获取“已发送标头”错误
- Symfony 2:404未找到当tryes打开/app_dev.php时出错
- PHP编程:PHP快速生成各种信息提示框的方法
- 使用theMovieDB用PHP显示图像海报