我来自 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();