Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> [PHP]funkcja która inną funkcję jako parametr
codex
post
Post #1





Grupa: Zarejestrowani
Postów: 35
Pomógł: 0
Dołączył: 29.11.2015

Ostrzeżenie: (0%)
-----


witam. powie ktoś jak mam napisać funkcję, która jako parametr przyjmuje adres innej funkcji. wszystko fajnie wychodzi w momencie gdy funkcja będąca parametrem jest bez argumentów - tu nie ma specjalnie filozofii. problem pojawia się wtedy gdy ta funkcja której adres ma być parametrem, ma przyjmować też argumenty - jak bym tego nie zapisał to wywala mi błędy :

  1. // funkcja której adres zostanie przekazany jako parametr:
  2. function service( $argx ) {
  3. echo '<br> service = '.$argx;
  4. }
  5.  
  6. // funkcja która ma przyjąć adres innej funkcji jako jeden z parametrów:
  7. function tester( $argx, $service ) {
  8. $service( $argx );
  9. return true;
  10. }
  11.  
  12. // wywołanie próbne:
  13. tester( 'message', service($x) );

jakoś w sieci nie widzę przykładów dla php ....
Go to the top of the page
+Quote Post
 
Start new topic
Odpowiedzi
vokiel
post
Post #2





Grupa: Zarejestrowani
Postów: 2 592
Pomógł: 445
Dołączył: 12.03.2007

Ostrzeżenie: (0%)
-----


  1. function service( ) {
  2. return "Service args: ".print_r(func_get_args(), true).PHP_EOL;
  3. }
  4.  
  5. function tester( $service ) {
  6. $args = func_get_args();
  7. unset($args[0]); // $service
  8. return call_user_func_array($service, $args );
  9. }
  10.  
  11. echo tester( 'service', 'arg-1' );
  12. /*
  13. Service args: Array
  14. (
  15.   [0] => arg-1
  16. )
  17. */
  18.  
  19. echo tester( 'service', 'arg-1', 'arg-2' );
  20. /*
  21. Service args: Array
  22. (
  23.   [0] => arg-1
  24.   [1] => arg-2
  25. )
  26.  
  27. */
Go to the top of the page
+Quote Post

Posty w temacie


Reply to this topicStart new topic
2 Użytkowników czyta ten temat (2 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Aktualny czas: 15.10.2025 - 06:15