简体   繁体   English

无法在PHP中将变量从一个函数传递给另一个函数?

[英]Trouble passing a variable from one function to another in PHP?

I have two functions and I am stumped on how to pass a variable between them. 我有两个函数,我对如何在两个函数之间传递变量感到困惑。 Here is what I have so far. 这是我到目前为止所拥有的。

function copy_photo ($image_url, $image_description){
$rand_string = rand(0001, 9999);//create simple random string   
$image_type = substr(strrchr($image_url,'.'),1);//get image type
$local_directory = "./images/";//folder to put photo
$local_image_name = $local_directory . $image_description . "-" . $rand_string . $image_type;//full directory and new image name to place photo 

copy($image_url, $local_image_name);// I want the function to first copy the image here
return $local_image_name;// <---this is the variable I want to pass on
}

function store_data ($local_image_name){
 //simple PDO statement to insert newly created local image url into database
}

copy_photo ($image_url, $image_description);//copy photos to folder 
store_data ($image_description);//store $image_description in database

What I would like to happen is for the copy_photo function to first copy the photo and then return $local_image_name and pass it to the store_data function for storage in a database. 我想发生的事情是,copy_photo函数首先复制照片,然后返回$ local_image_name并将其传递给store_data函数以存储在数据库中。 I keep getting an error that $image_description is null when store_data tries to store it into the database. 当store_data尝试将其存储到数据库中时,我不断收到$ image_description为null的错误。 How can I successfully pass $local_image_name from one function to the next? 如何将$ local_image_name从一个函数成功传递给另一个函数?

Thanks!! 谢谢!!

You assign the return value of the function to a variable, then pass that variable to the next function. 您将函数的返回值分配给变量,然后将该变量传递给下一个函数。

$image_name=copy_photo ($image_url, $image_description);//copy photos to folder 
store_data ($image_name);//store $image_description in database

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM