1

How to send an object as paramater in a function call? I don't want to instantiate the object when passing it, so myFunction( new myObject() ) wouldn't work.

I want myFunction to be able to instantiate the object later. I'm just not sure how to pass a class around in this manner.

0

2 Answers 2

3

Pass the class name as a string, and instantiate it.

https://stackoverflow.com/a/4578343/362536

function ($className) {
    $object = new $className();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ah! I thought as much but I thought there may be another way without using strings. It works though. Good enough for me. Thank you.
2

You could pass a string and do:

myFunction($class) {
    $object = new $class();
}

But a better OOP approach would be to pass a factory object and let the factory create the object:

class MyFactory {
    public function create() { 
        return new myObject; 
    }
}

myFunction(MyFactory $factory) {
    $object = $factory->create();
}

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.