我有以下PHP OOP代码,在此我试图向用户发送一条消息,说图像太大了。
我真的找不到令人满意的答案,可以帮助我。
这是一个显示我如何尝试的例子。
有人能指出我这样做的正确方向吗?
图像类:
class image{
public function checkImageSize($img){
if($img['size'] > 1500000)
{
return false;
}
}
}// end class image
HTML方面
<?php
if(isset($_POST['submit']) && $_SERVER['REQUEST_METHOD'] === 'POST')
{
$img = new image;
$img->checkImageSize($_FILES['image']);
$img->otherfunctions();
$img->anotherfunction();
}
?>
只需将return true;
添加到函数的末尾,然后检查它:
if($img->checkImageSize($_FILES['image'])) {
$img->otherfunctions();
$img->anotherfunction();
} else {
echo "TOO BIG!!!";
//header("location: somewhere");
exit;
}
或者相反:
if($img->checkImageSize($_FILES['image']) === false) {
echo "TOO BIG!!!";
//header("location: somewhere");
exit;
}
$img->otherfunctions();
$img->anotherfunction();
作为课程的延伸,你可以做到这一点
<?
//Array for storing data for class to access
$info = array(
"image" => null
);
//array of errors to be returned
$errors = array(
"size" => null,
"other" => null
);
//Set the image
function SetImage($img){
$this->info["image"] = $img;
}
//Check size of image
function CheckSize(){
if($this->info["image"] > 1500000){
//If image is too large populate error
$this->errors["size"] = "File is too large";
}else{
continue;
}
}
//Check other things
function OtherCheck(){
if(true){
continue;
}else{
$this->errors["other"] = "Other checks failed";
}
}
//Check if there are any errors
function CheckErrors(){
for($i = 0; $i < count($this->errors);$i++){
if($this->errors[$i] != null){
//if the value of an error is not null then return true
//because there is an error present
return true;
}
}
}
//Run all checks
function RunChecks(){
CheckSize();
OtherCheck();
//Check if CheckErrors() returns true
if(CheckErrors()){
//If it returns true then print the error array
print_r($this->errors);
}
}
?>
在OOP方法中,我更愿意让班级完成所有繁重的工作
使用此代码现在看起来像这样
$img = new image;
$img->SetImage($_FILES["image"]);
$img->RunChecks();