Luís Ramalho
Luís Ramalho

Reputation: 23

Call function from outside a class

I am trying to call a function from outside a class and having problems:

class Factorial{

    public function factorial($number) {
        if ($number < 2) {
            return 1;
        } else {
            return ($number * factorial($number-1));
        }
    }
}

$f = new Factorial();
echo $f->factorial(5);

Can someone please point me in the right direction?

Thank you so much

Upvotes: 2

Views: 5050

Answers (2)

Michael Petrov
Michael Petrov

Reputation: 2317

$this->factorial($number-1) is what you want to call the class method. The code is getting confused because you named the class the same thing as the function (and it thinks it's a constructor).

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 817208

Your problem is not outside, but inside:

public function factorial($number) {
    if ($number < 2) {
        return 1;
    } else {
        return ($number * $this->factorial($number-1));
    }
}

If you want to refer to another method you have to use $this->methodname where $this refers the instance:

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs (...))

I suggest to read PHP - OOP - The Basics.

Upvotes: 3

Related Questions