PHP Static methods

I will talk about static methods usages in php with some code samples. Lets get started.

Here is a sample, calling static function outside of the class.

<?php
class welcome {
  public static function sayHi() {
    echo "Welcome!";
  }
}

// we can like this -> className::methodName()
welcome::sayHi();
?>

We can also call within the class like this using self::

<?php
class welcome {
	public static function sayHi() {
		echo "Welcome!";
	}
	public function msg() {
		self::sayHi();
	}
}

$hi = new welcome();
$hi->msg();
?>

You can also call static methods from another class like this

<?php
class welcome {
  public static function sayHi() {
    echo "Welcome!";
  }
}

class anotherClass {
  public function msg() {
    welcome::sayHi();
  }
}

$var = new anotherClass();
$var->msg();
?>

You can choose any ways depending upon the situations, the result will still be the same.

By Yuuma



アプリ関連ニュース

お問い合わせはこちら

お問い合わせ・ご相談はお電話、またはお問い合わせフォームよりお受け付けいたしております。

tel. 06-6454-8833(平日 10:00~17:00)

お問い合わせフォーム