1

REVISED

I have a simple question, but being new to OOP I am not sure if this is possible.

Currently I have a class with one function that accepts an argument. What the actual function does is irrelevant.

<?php
class Method {

    public function show($parameter){
        echo $parameter;
    }

}
?>

I create the object like this...

$this->Method = new Method();

And use it like this...

$this->Method->show($parameter);

So the question is, can my function be set up in a way to simplify the use to this...

$this->Method($parameter);

I tried by changing the function to a __construct and using the above line of code but it fails since the new Method() was created without a $parameter specified.

I was hoping to be able to pass the $parameter after the new Method(); was called.

3
  • What would $this->Method($parameter); do in this example? Commented Aug 20, 2015 at 23:25
  • @Don'tPanic Well...nothing...that's my issue, haha Commented Aug 20, 2015 at 23:39
  • Well, it potentially can do something, but I'm just not certain what you had in mind. If you want it to be callable, you can give it an __invoke method, but I don't know if that's what you intended. Commented Aug 20, 2015 at 23:47

1 Answer 1

2

Yes, you can do this. If you add an __invoke() method to your class, instances of that class can be called like you would a method.

class Method {
    public function __invoke($param) {
        echo $param;
    }
}

Then you can use it in your class the way you want to

$this->Method = new Method;
$this->Method('something');  // echos something

If you still want to have the show method (or whatever the method actually is) as well, you can leave it there and just call it in __invoke instead.

class Method {
    public function show($param) {
        echo $param;
    }
    public function __invoke($param) {
        $this->show($param);
    }
}

Another possibility, because it looks like you are wanting to be able to use an object like you would use a function, is to define a trait and use it in the object that currently has a Method instead of using a Method class. If you create a trait like:

trait CanUseMethod {
    public function Method ($parameter) {
        echo $parameter;
    }
}

Then in the class that needs to use Method, instead of

$this->Method = new Method;

You can use the trait like this:

class Example {
    use CanUseMethod;
}

Then your Example class will be able to use Method without creating a new object.

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

1 Comment

Great! I had a feeling there was a magic method I could use. I kept trying within __construct with no luck. Thank you again!

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.