私はこの機能を書いており、これを使って自分のローカルサーバーに画像を動的にアップロードしています。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関数を使用しています。
if($moveFile){
return true;
}
は私が本当の代わりに$image_name
を返すこともできますが、私はそれが内側なので、私が使用できるようにそれをキャッチしたいかわからないよ:
$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ステートメント。
特定のデータをどのように返すことができますか、それらのニーズに合わせてコードを書き直す方法の提案は素晴らしいでしょう。
あなたが言った正確に何をすべきか、 '$ image_name'または' getImageName() 'のようなメソッドを作成し返します。 – Rasclatt
@Rasclattイメージ名を取得するメソッドを作成することに気をつけませんでした。ガイダンスをありがとう。 – Craig