2

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 ?

6
  • Is it different ? Yes the one is wrong and the other one correct. You don't have a static method here, so you need to use ->. And $a = new Test; or $a = new Test(); is right ? Both. If you want to pass arguments to the constructor then of course you have to write the parentheses. Commented Apr 20, 2016 at 3:09
  • I use $result = Test::printword($w); and it still run ? Commented Apr 20, 2016 at 3:10
  • use public static function printword() Commented Apr 20, 2016 at 3:11
  • @Fil can you explain ? Commented Apr 20, 2016 at 3:12
  • Yes it does, but it's wrong. Turn on error reporting and you get a warning about it Commented Apr 20, 2016 at 3:12

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Can a ask, so do we should use all static function, because it looks simple, easy to use, and do not need to instantiation ?
Actually, No, use a static method when it's complete itself and not depended to others properties of the class (like, for instance, a syntax converter for BB code to HTML)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.