我有以下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();
}
?>
答案 0 :(得分:2)
只需在功能的末尾添加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();
答案 1 :(得分:2)
作为您课程的扩展,您可以这样做
<?
//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();