How to call a function or method inside its own cl

2020-03-08 08:18发布

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;
 }
}

4条回答
姐就是有狂的资本
2楼-- · 2020-03-08 08:46

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楼-- · 2020-03-08 08:47

You can use class functions using $this

<?php
    class A{

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

     function c(){
       $m = $this->b('Mesage');
       echo $m;
     }
    }
查看更多
家丑人穷心不美
4楼-- · 2020-03-08 08:51

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(){}
查看更多
beautiful°
5楼-- · 2020-03-08 08:57

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).

查看更多
登录 后发表回答