0

I have a function that is called like this:

foo($object->ID);

and in the function I need to somehow select $object if $object->ID is passed as a variable.

function foo($id = NULL){
  if($id != NULL) ... // here I want to get $object
  else ...
}

How can I do this?

4 Answers 4

5

That is not possible. You are passing a number without any information about its origin. Do this

foo($object)

function foo($object){
   if($object->ID !== null) ... // work with $object
   else ... // work with ID

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

Comments

4

why not:

foo($object);

and

function  foo($localObject){
  if(isset($localObject->id)){
  }
}

Comments

2

You need to pass the object in as an argument instead of the ID.

1 Comment

You should just pass the object in, and get ID from that object, not add another parameter.
1

If I understand what you're asking correctly, why not just pass the object itself by ref?

function foo(&$obj)
{
    if($obj != NULL && $obj->ID != NULL)
    {
       // ...process your stuff 
    }
}

My PHP's pretty rusty, but I'm fairly sure that's how you pass by ref...

7 Comments

Pass-by-ref is not relevant in this case.
I should clarify: You want to make sure that you pass the object by reference so that you don't make an entirely new copy of it.
well the reason is pretty stupid :) I have a set of functions that all but this one take the $object->id as argument. And it looks ugly if just this one didn't :)
since php 5 (maybe earlier than that), objects are always passed by reference - no need to explicitly pass objects by ref.
There's a typo: it should be $obj, not &obj on line 3.
|

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.