我寫了這個函數,我用它來動態地上傳圖片到我的本地服務器。如何查看並返回if語句中使用的函數的結果?
我跑進了以下問題,是它裏面產生的$image_name
,所以當我打電話uploadImage function
我不能返回$image_name
,這樣我可以將其插入到數據庫中,我不知道如何返回變量。
public function uploadImage($data, $uploadLocation, $nameTag){
if($data['size'] != 0) {
$errors = array();
$maxsize = 16777216;
$acceptable = array(
'image/jpeg',
'image/jpg',
);
$image_extension = pathinfo($data['name'], PATHINFO_EXTENSION);
//image_name variable I'm referring to
$image_name = uniqid($nameTag, true) . '.' . $image_extension;
if($data['size'] >= $maxsize) {
$errors[] = 'File too large. File must be less than 16 megabytes.';
} else if($data['size'] == 0){
$errors[] = 'You need to upload an image.';
}
if((!in_array($data['type'], $acceptable)) || (empty($data['type']))) {
$errors[] = 'Invalid file type. Only JPG, GIF and PNG types are accepted.';
}
if(count($errors) === 0) {
$moveFile = move_uploaded_file($data['tmp_name'], $uploadLocation . '/' . $image_name);
if($moveFile){
return true;
}
}
}
return false;
}
這裏我使用uploadImage函數。
$uploadImage = new UploadImages();
if($uploadImage->uploadImage($data['image_data'], 'uploads/img/instructions', 'instruction_')){
//here I'd like to return the $image_name from the function
//I'm using PDO to insert the name in database
$sth = $db->prepare('UPDATE instructions SET image = :image WHERE id = :id');
$sth->bindValue(':image', //name returned from the function, PDO::PARAM_STR);
$sth->bindValue(':id', $instructionsId, PDO::PARAM_INT);
$sth->execute();
}
我計算過,在一段代碼:
if($moveFile){
return true;
}
我可能會返回$image_name
,而不是真實的,但我不能確定如何我抓住它是可用的,因爲它是內部的如果聲明。
任何想法我們如何能夠返回這些特定的數據,或者如何更好地重寫代碼以適應這些需求的建議將是非常好的。
你做你說什麼,回'$ image_name'或創建一個像'getImageName()'方法。 – Rasclatt
@Rasclatt它並沒有想到創建一個獲取圖像名稱的方法。感謝您的指導。 – Craig