Search code examples
phpfunctionclasscall

Is it different between two way to call a function in an other class?


I have a class

<?php
class Test{
    public function printword($word){
         echo $word;
    }
}
?>

And in another class, i call it.

<?php
//Included needed files !!!
$w = 'Hello';

//Way 1
$a = new Test;
$result = $a->printword($w);

//Way 2
$result = Test::printword($w);
?>

Is it different ?

And $a = new Test; or $a = new Test(); is right ?


Solution

  • Yes, it's different. if you declare a method static makes them accessible without needing an instantiation of the class.

    class Test{
        public function printword($word){
            echo $word;
       }
    }
    
    //Call printword method
    $a= new Test();
    $a->printword('Words to print');
    

    Static Method:

    class Test{
        public static function printword($word){
            echo $word;
       }
    }
    
    //Do not need to instantiation Test class
    Test::printword('Words to print');
    

    See the documentation.