1

Is it possible to implement functions as object instances in PHP? I'm used to doing this in Java with the code below, but I can't seem to find a similar approach in PHP. Is it possible?

interface OneVarFunction {
    public int eval(int x);
}
static void routine() {
    OneVarFunction func1 = new OneVarFunction() {
        public Boolean eval(int x) {
            return x*x;
        }
    };
    OneVarFunction func2 = new OneVarFunction() {
        public Boolean eval(int x) {
            return 2*x+1;
        }
    };
}

1 Answer 1

2

It is possible in PHP7+

in your case, an example would be

interface OneVarFunction {
    public function eval($x);
}

//...

$test = new class implements OneVarFunction {
    public function eval($x) {
        return $x*$x;
    }
};

For more information, see the corresponding site of the PHP Manual, which also provides further examples.

It is not possible in versions prior to PHP7, though.

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

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.