Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
 }
}
like image 727
zgrizzly_7 Avatar asked Nov 28 '25 14:11

zgrizzly_7


2 Answers

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;
 }
}
like image 189
John Conde Avatar answered Nov 30 '25 05:11

John Conde


You can use class functions using $this

<?php
    class A{

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

     function c(){
       $m = $this->b('Mesage');
       echo $m;
     }
    }
like image 39
Double H Avatar answered Nov 30 '25 06:11

Double H



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!