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.
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!';
}