0

So I currently have a class and wanted to make class calls cleaner by being able to call the class instance as a function, like the __toString magic method which outputs a string when called, instead be able to call $instance() as a function and have it called.

Like:

class MyClass {
  public function __onCall() {
    echo 'This was called when the user called the instance!';
  }    
}

$instance = new MyClass();
$instance();
//opts: This was called when the user called the instance!

Essentially I want to be able to chain class functions and cut off one chain that'll be called a lot by calling a function from the instance.

Syntax I want:

$Class('Some String')->SomeFunction()->AnotherFunction();

Syntax I have:

$Class->select_string('Some String')->SomeFunction()->AnotherFunction();

:-)

Jack Hales
  • 1,574
  • 23
  • 51
  • I'm not quite sure why you really need to have a structure like this when in fact you are dealing with OOP. – Aldee Dec 04 '16 at 06:06
  • @Aldee This isn't the exact way it's being used, it's meant to do a call like: `$string('TestString')->AnotherCall()->MoreCalls()`, since that's easier syntax than `$string->select_string('TestString')->AnotherCall->MoreCalls()` if that makes sense, so that's the reason I wanted to use this method. `:-)` – Jack Hales Dec 04 '16 at 06:07
  • Please check my answer below :-) – Aldee Dec 04 '16 at 06:15

1 Answers1

1

Ok. I see what you mean here. So you want to have a fluent method chaining. This is actually answered by another thread

Hope this helps.

Community
  • 1
  • 1
Aldee
  • 4,439
  • 10
  • 48
  • 71
  • Aha yeah I know how to chain methods, I just want to cut one chain off by being able to call a function that'll be called a lot directly from the instance of the class, I'll add that to my question. :~) – Jack Hales Dec 04 '16 at 06:17
  • Ahh. okay, I see. I suppose this might be of interest for you http://php.net/manual/en/language.oop5.anonymous.php - but this is for PHP 7 only I guess. – Aldee Dec 04 '16 at 06:19
  • Ahah I found it, didn't think to look at the magic methods, `__invoke`! http://php.net/manual/en/language.oop5.magic.php#object.invoke – Jack Hales Dec 04 '16 at 06:25