0

I got this function from a question here. when I try on a separate file it runs normally. but when I rewrite it in a class that contains more functions I can rather call it in another file, the searchRec contained in this function (calling the function itself) turns red or is marked as an error by visual studio code. whereas before, above this function I also wrote the same function in which there is a function call itself, and it runs normally.

public function searchRec($haystack, $needle, $pathId=Array(), $pathIndex=Array())
{
    foreach($haystack as $index => $item) {
         
        $pathId[] = $item['Id'];
        $pathIndex[] = $index;
     
        if ($item['Title'] == $needle) {
    
            $returnObject = new stdClass();
             
            $returnObject->match = $item;   
            $returnObject->pathId = $pathId; 
            item directly
                $returnObject->pathIndex = $pathIndex; 
            return $returnObject;
        }
        
        if(isset($item['Children']) && count($item['Children']>0)) {
            (recursively) 
           
                $result = searchRec($item['Children'], $needle, $pathId, $pathIndex); //searchRec error, VCS says: undefined function
    
            if ($result) {
       
                return $result;
            }
        }
    }
    return false;
}

1 Answer 1

1

Since it's a class method, you need to call it with object-oriented syntax.

$result = $this->searchRec($item['Children'], $needle, $pathId, $pathIndex);
Sign up to request clarification or add additional context in comments.

2 Comments

what I'm confused about is, why when I run this code in a separate file I don't need to add $ this->?
When you called the function you had to use $something->searchRec(...) didn't you? It's a class method, it has to be called on an 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.