How to call a function or method inside its own class in php?

被刻印的时光 ゝ 提交于 2019-12-06 15:11:27

问题


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(){}


来源:https://stackoverflow.com/questions/33437233/how-to-call-a-function-or-method-inside-its-own-class-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!