Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function inside a class from within a function in the same class? [duplicate]

Tags:

php

class

I am new to PHP classes and I am wondering how I can call a function which resides in the same class I am calling it from. Is this right or the best approach?

page1.php:

 $object=new MyClass();
 $object->func1(); 

MyClass.php:

class MyClass{

    function func1(){
        ....
         $object->func2();
    }

    function func2(){
        ....
    }

}

The reason I want to do this is because func1 will call func2 at the end of func1 but I will also need to use func2 independently of func1 in other circumstances and I thought if this is possible it will cut down on the code(even though it would be a simple copy/paste from func2 and place it at the end of func1).

Edit: or could I use:

self::func2();
like image 534
Drew Avatar asked Nov 28 '25 06:11

Drew


1 Answers

You can use $this to refer to the current object, and thus call $this->func2().

(The value of $this is automatically populated by PHP when you're in an object instance's context.)

like image 74
Amber Avatar answered Nov 30 '25 19:11

Amber