How to call a function or method inside its own cl

2020-03-08 07:52发布

问题:

I declare my class in PHP and several functions inside. I need to call one of this functions inside another function but I got the error that this function is undefined. This is what I have:

<?php
class A{

 function b($msg){
   return $msg;
 }

 function c(){
   $m = b('Mesage');
   echo $m;
 }
}

回答1:

You can use class functions using $this

<?php
    class A{

     function b($msg){
       return $msg;
     }

     function c(){
       $m = $this->b('Mesage');
       echo $m;
     }
    }


回答2:

This is basic OOP. You use the $this keyword to refer to any properties and methods of the class:

<?php
class A{

 function b($msg){
   return $msg;
 }

 function c(){
   $m = $this->b('Mesage');
   echo $m;
 }
}

I would recommend cleaning up this code and setting the visibility of your methods (e.e. private, protected, and public)

<?php
class A{

 protected function b($msg){
   return $msg;
 }

 public function c(){
   $m = $this->b('Mesage');
   echo $m;
 }
}


回答3:

You need to use $this to refer to the current object

$this-> inside of an object, or self:: in a static context (either for or from a static method).



回答4:

To call functions within the current class you need to use $this, this keyword is used for non-static function members.

Also just a quick tip if the functions being called will only be used within the class set a visibility of private

private function myfunc(){}

If you going to call it from outside the class then leave it as it is. If you don't declare the visibility of a member function in PHP, it is public by default. It is good practice to set the visibility for any member function you write.

public function myfunc(){}

Or protected if this class is going to be inherited by another, and you want only the child class to have those functions.

protected function myfunc(){}