Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference of using static between java and PHP?

Tags:

java

php

static

In Java i read that, static function can access only static function or static variable. I was trying to find out the difference of using static in PHP and java.

  1. Does the same is also in PHP?
  2. Can we call non-static function inside the static function, in PHP?
like image 434
Rahul Avatar asked Jul 12 '26 10:07

Rahul


2 Answers

Can we call non-static function inside the static function, in PHP?

Yes but not adviced. As $this keyword won't be available under static context. However, you can do that using the static / self keyword but that will result in a Strict standards notice

Strict standards: Non-static method A::foo() should not be called statically

Demonstration on Code Viper

So better not do it !

like image 186
Shankar Narayana Damodaran Avatar answered Jul 14 '26 23:07

Shankar Narayana Damodaran


  1. I think it's the same.

BTW, EDIT for STATIC functions (didn't read correctly...)

For Java, a static variable will survive throughout the whole life when JVM is running or when class is unloaded using some techniques. That means, once the static variable is used, it will exist in memory.

PHP hasn't any memory. So, the variables, which is even declared as "static" or "Global", will be destroyed...

for the 2. Yes. If the instance of your class is rarely needed, you can have the static method create an instance, call the non-static method and return the value.

class Scope {
    public function mynonstatic() {
    }

    public static function mystatic() {
        $s = new Scope();
        return $s->mynonstatic();
    } }

Remember that a static method is really just a global function with reduced scope. They are useful, but are should not be created without good reason.

Source here : http://yiyujia.blogspot.ro/2010/09/static-variable-in-php-vs-static.html

like image 21
Florian Doyen Avatar answered Jul 15 '26 00:07

Florian Doyen



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!