0

Suppose i had defined a function which fetch the data from database and display it.

i.e.

show_name();

now i need to use this function in a php page four times.

Now my question is when i call this function four time will it fetches the data from database on every call and then display it ?

if yes will it be better to store the result in a $variable and then use that $variable four time instead of calling a function four time.

Please guide thanks :D

4
  • 4
    You can use object to store the datas get by your function Commented Jan 28, 2016 at 12:56
  • 4
    I think it's better to store data in a variable as long as you are sure the data will be the same between function calls. There is no need to ask database four times to get the same result. Commented Jan 28, 2016 at 13:00
  • 1
    We don't know. Does it fetch the data every time it's called? Then yes. PHP doesn't do any implicit caching, it does exactly what you tell it to. If you tell it to make a database query in that function, then it will do that. Every time. Commented Jan 28, 2016 at 13:01
  • In the function definition of show_name() there is a sql query which fetches the name from the database. So when we call it four times in a page it will fetch the database four time for the same name. i think this is not a good programming practice ? Commented Jan 28, 2016 at 13:09

2 Answers 2

1

I'll cache results of that function to be consistent during the page processing. But when it's intended to work with values that can be changed during page proccesing you should get the data over and over again. Take into consideration - at least for MySQL (if it's your case) that there is a query cache which can help you.

Sign up to request clarification or add additional context in comments.

2 Comments

The show_name() function will show the same data on every four function call. what i want to know is that is it good to use that function four times. if i do it will request the database four times. am i right
It depends how you will implement show_name(). If you will not bother about implementing some kind of cache inside it will definitely call SQL query everytime you call it.
1

if you call function 4 times then all time database query will execute... so if possible, store value in variable and use it 4 times

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.