doujian3132 2013-04-27 11:33
浏览 36

验证时类构造函数错误

I am developing a file uploaded class, and trying to perform few validation before other codes, but its returning all vars instead of false, check following code....

class FileUploader
{

   private $filePath;

   function __construct($file_path) {

      if(file_exists($file_path)) {

           $this->filePath = $file_path;

      }

     else return false;

   }

}

When I am using this class like following....

$file_path = getcwd().'\img.pn'; //invalid path

$file_uploader = new FileUploader($file_path);

if($file_uploader) {
    //process
}
else {
    echo 'Invalid File Path!';
}

But it doesn't echo Invalid File Path as expected, when i tried var_dump, it returned following output...

  object(FileUploader)[1]
  private 'filePath' => null

Please help to fix this. thanks.

  • 写回答

1条回答 默认 最新

  • dongtazu3080 2013-04-27 12:11
    关注

    You might consider using an exception in the constructor as constructors should no return anything. (Have a look at this question).
    Otherwise you may create a function to check the file_path :

    class FileUploader
    {
    
       private $filePath;
    
       function __construct($file_path) {
          $this->filePath = $file_path;
       }
    
    
    
       function isValidFilePath() {
          return file_exists($this->file_path);
       }
    
    }
    

    and then :

    $file_path = getcwd().'\img.pn'; //invalid path
    
    $file_uploader = new FileUploader($file_path);
    
    if($file_uploader->isValidFilePath()) {
        //process
    }
    else {
        echo 'Invalid File Path!';
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分