Skip to content
Advertisement

PHP: Can I store a function in a class object and pass values to it for the function to interpret. Python can do it, but can PHP?

I’m having a hard time figuring out how to implement code similar to the following Python code:

JavaScript

Essentially it creates an array of _Mapper objects and each object contains a reference to a function (either function1 or function2) which is later used to calculate a value. The crucial steps seems to be:

JavaScript

which takes the function held in _Mapper.estimator and then passes oldValue to as if it was newValue = function1(oldValue) or newValue = function2(oldValue)

I’m trying to implement something similar in PHP but I seem to get some kind of infinite loop when running this in the CLI. It appears that the function name is not stored in the

JavaScript

I’m sure that I’ve made a simple mistake but I can’t see what I’ve missed. How can I store a function name in an object and then pass a parameter into it so that the stored function uses that parameter and returns a value ?

Advertisement

Answer

There are two issues :

in your _create_couplet method, the argument you’re giving to new _Mapper() is not the function to execute, but the function result. You’re executing $pairing->function1() and it performs null * 2 because you’re allowing null values, otherwise it should have failed because you’re calling function1 without argument.

As Lars suggested you should use a callable argument :

JavaScript

THe second issue which provokes the infinite loop is that you try to call this callable in the estimator method, which is calling $this->estimator(). You may think that $this->estimator() refers to your callable contained in $this->estimator, but as you have a method with the same name, PHP will think you’re calling the method and not the property.

THe simplest way to fix it is to name either the method or the property differently.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement