0

I need to define the type of passed variable as an generic object, how?

Tried:

public function set($service = null, (object) $instance) {
    [..]
}

Can stdClass help? How?

Thanks!

3 Answers 3

1

Nope, in php all classes aren't derive from the common ancestor.

So doubtfully you can use current php's implementation to state "object of any class"

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

3 Comments

So, solution only inside the function with is_object?
@Gabriel Santos: yes. Or, if you could, just create interface and implement it in each required class
No, interface in this case is so ugly. Thanks for help!
1

No, the object has to be some class. You can give the any class name as object's type

public function set($service = null, ClassName $instance) {
    //now the instance HAS to be the object of the class
}

Or a basic trick would be to create a basic class yourself

Class GenericObject {}
$myobj = new GenericObject();
$myobj -> myCustomVar = 'my custom var';

//Now send it
public function set($service = null, GenericObject $instance) {
   [...]
}

1 Comment

Thanks for samples, but, it is for a Service Locator, which will not work correctly with this approach.
0

Gabriel,

if what you want to do is check if the variable is an object, you could do this:

public function set($service = null, $instance) {
    if (!is_object($instance)) return null; //or whatever
    [..]
}

What are you trying to prevent with that? With your declaration, you would get an exception if the variable is not an object (it will not cast it).

4 Comments

I have a "exception catcher".
I know about is_object inside set function, but I thought about casts.
@Gabriel Santos: to be precise it has nothing to do with "casts" in php, it is called "type hinting"
function set($service = null, (object) $instance) casting $instance as Object

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.