私は Ruby の世界から来て、現在取り組んでいる PHP プロジェクトを持っています。
Ruby スクリプトのように、PHP でクラス メソッドを宣言することは可能ですか? 基本的に、私は次のコードに相当するものをPHPで尋ねています
class A
def hello; "hello from object"; end
def self.hello; "hello from class"; end
end
インスタンス メソッドとクラス メソッドの違いに注意してください。
私は Ruby の世界から来て、現在取り組んでいる PHP プロジェクトを持っています。
Ruby スクリプトのように、PHP でクラス メソッドを宣言することは可能ですか? 基本的に、私は次のコードに相当するものをPHPで尋ねています
class A
def hello; "hello from object"; end
def self.hello; "hello from class"; end
end
インスタンス メソッドとクラス メソッドの違いに注意してください。
class A
def hello; "hello from object"; end
def self.hello; "hello from class"; end
end
class A {
// attributes or properties
public $age;
private $gender;
protected $location;
// needs to be static to be called as self:: inside the class
public static function hello(){
return "hello from object";
}
// use this keyword to be called inside the class
public function hello1(){
return "hello from object";
}
public function hello2(){
print(self::hello());
print(this->hello1());
}
// How about private method
private function hello3(){
return "hello world";
}
}
Calling Outside the class
$instance = new A();
//static
$instance::hello();
//non static
$instance->hello1();
$instance->hello2();
PHP では、クラス メソッドは通常、静的メソッドと呼ばれ、そのように宣言されます。あなたの例を直接翻訳するには: -
class A
{
public function hello()
{
return "hello from object";
}
//We can't have two methods with the same name.
public static function s_hello()
{
return "hello from class";
}
}
次に、次のようにメソッドを呼び出します:-
//For a static method we don't need an instance
echo A::s_hello;
//But we do for an instance method
$a = new A();
echo $a->hello();
静的プロパティを使用することもできるため、上記の例は次のように変更できます。
class A
{
private static $s_hello = "hello from class";
private $hello = "hello from object";
public function hello()
{
return $this->hello;
}
//We can't have two methods with the same name.
public static function s_hello()
{
return self::$hello;
}
}
PHPには、単一のクラスで同じ関数の複数の定義を持つ方法はありません
むしろあなたはこれを行うことができます
abstract class A{
static function hello()
{
return 'hello';
}
}
class B extends class A
{
function hello()
{
return 'hello from Object';
}
}
A::hello();
$t = new B();
$t->hello();