0

I have this class:

class testclass{
    function func1(){
        return "hello";
    }
    function func2(){
        echo func1();
    }
}

When I am running

$test = new testclass();
$test->func2();

I get an error: Fatal error: Call to undefined function func1() with the line index of echo func1();

My question now is, how do I make the func2 recognize func1

Is this a problem with the scopes?

1
  • 1
    func1() refers to the global function func1(). Not the func1() of the current class. To call the func1() in the current class you'd use $this->func1() (or self::func1() if it's a static method) Commented Apr 29, 2014 at 10:46

3 Answers 3

5
function func2(){
        echo func1();
    }

should be

function func2(){
        echo $this->func1();
    }

http://www.php.net/manual/en/language.oop5.visibility.php

self:: vs className:: inside static className metods in PHP

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

3 Comments

and where is the difference to echo testclass::func1() ?
The :: operator indicates that func1() is a static method of testclass, which isn't the case.
You can check more about this here stackoverflow.com/questions/3481085/…
1

You're using OO techniques, so you'll have to use the $this keyword to access the func1() function:

class testclass
{
    function func1()
    {
        return "hello";
    }
    function func2()
    {
        echo $this->func1();
    }
}

Comments

0

You have error in your code, you cannot invoke the function like this, the proper way is by using $this (which refers to the class itself):

class testclass
{
    function func1()
    {
        return "hello";
    }
    function func2()
    {
        echo $this->func1();
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.