0

I have a couple of function share the same value, so I was thinking about a way to put the value of a function, then all function could share these values, but I am encountering an issue that the I could not pass these value into the function. Do you have any better way to achieve this or do you think I should just type each value inside each function?

<?php
$current_user=get_current_user_id();
$display_user= bp_displayed_user_id();

function vote_my_faith($current_user,$display_user){
    echo $current_user;
    echo $display_user;
}
?>
Dave Chen
  • 10,887
  • 8
  • 39
  • 67
conan
  • 1,327
  • 1
  • 12
  • 27
  • 2
    If many functions require the same two variables, you should probably wrap them in a class and have the two variables as attributes of the class. – Dave Chen Apr 08 '15 at 19:23
  • As Dave said you could use a class and set properties to reuse later. Sometimes a static class is the way to go if you dont need an instance. Just a note on your code: It's bad practice to echo stuff inside a function. You should return the values from the function using return keyword. – mindore Apr 08 '15 at 19:31
  • See the duplicate for the general explanation about variable scope. As the two above mention, additionally look into classes, as it sounds like what you need. – deceze Apr 08 '15 at 19:58
  • mindore, how should I return a values from the function using return keyword, could you provide a simple example, appreciate. Any why it's bad to echo stuff inside a function? – conan Apr 08 '15 at 20:05
  • Its bad because its harder to do stuff with the result and to reuse the function. `function vote_my_faith($current_user, $display_user) { return array('user' => $current_user, 'display' => $display_user); } $values = vote_my_faith($current_user, $display_user); echo $values['user']; echo $values['display'];` – mindore Apr 12 '15 at 19:27
  • And regarding the comment Dave made about a class. You could create a class like this and save data in class properties so you can get it later on same page load. `class User { public $user_id = null; public function get_current_user_id() { if ($this->user_id !== null) { return $this->user_id; } else { // Make a database query or other "expensive" stuff here. } } }` – mindore Apr 12 '15 at 19:44

0 Answers0