HiFlyer Ojt
HiFlyer Ojt

Reputation: 31

PHP: Returning function value by itself not working

I have a function inside of a class, every time I use I got error undefined function in_array_r() inside of foreach. But when I use it outside of the class as normal function it works. I want to use this inside of the class so I will not call in every page.

public function in_array_r($needle, $haystack, $strict = false) {
        foreach ($haystack as $item) {
            if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
                return true;
            }
        }
        return false;
    }

Upvotes: 1

Views: 40

Answers (2)

nfproductions
nfproductions

Reputation: 94

You need to assign the method to the object.

$this->in_array_r();

Upvotes: 1

Nathan Dawson
Nathan Dawson

Reputation: 19308

The function is recursive - it's calling itself. When you put it inside a class (as a method), you need to update the reference to in_array_r() within the method body.

This:

. . .(is_array($item) && in_array_r($needle, . . .

Becomes:

. . .(is_array($item) && $this->in_array_r($needle, . . .

Upvotes: 1

Related Questions