Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Using a method as a callback

Tags:

oop

php

I was trying to use array_walk_recursive for something, and wanted to use one of the class' methods as the call back, so trying:

  array_walk_recursive($TAINTED, "$this->encode()");

and variations thereof all failed. I eventually settled for:

array_walk_recursive($TAINTED, 'className::encode');

which works, but I've read on here that calling class methods in a static fashion like this is often considered poor practice. Or is this one of those situations where it's necessary?

So, is this the right way to go about it, or is there a way to put in the callback function without having to fall back on using it as a static class method?

like image 234
Stomped Avatar asked Dec 13 '22 21:12

Stomped


2 Answers

array_walk_recursive($TAINTED, array($this, 'encode'));
like image 67
webbiedave Avatar answered Dec 24 '22 05:12

webbiedave


I know this thread is older but by reading your words "calling class methods in a static fashion like this is often considered poor practice" I have to say that static functions are a good practice when used for the right task. Frameworks like Laravel and Symphony shows the true potential of static methods.

Anyways when you aren't afraid of using static methods you can call your method using self instead of specifying the class name that might change during development process.

array_walk_recursive($TAINTED, 'self::encode'); 
like image 23
Hexodus Avatar answered Dec 24 '22 05:12

Hexodus