theman26 theman26 -4 years ago 79
PHP Question

OOP PHP: Calling classes as functions after creating an instance of them

What I would like to do after creating an instance of a class is to be able to call the name of that instance as a function. For example, consider the following class Foo:

$bar = new Foo(5); // generates 5 random ints between 0-100
bar(3); // get the third int in the object bar


Is this even possible in PHP or would it involve messing with the parser? Thanks in advance!

Answer Source

What this question is really about is creating a PHP functor and here's an example I lifted from here:

<?php

class SquareCallback
{
    public function __invoke($value)
    {
        return $value * $value;
    }
}

$squareObject = new SquareCallback;
var_dump($squareObject(3));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download