Heim > php教程 > php手册 > Hauptteil

PHP使用静态方法的几个注意事项,php静态

WBOY
Freigeben: 2016-06-13 09:25:21
Original
951 Leute haben es durchsucht

PHP使用静态方法的几个注意事项,php静态

本文实例介绍了PHP使用静态方法的几个常见注意事项。分享给大家供大家参考。具体方法如下:

1. 即使类中的方法并未用static声明,但其未使用到可改变的类成员变量,在外部仍可用操作符::来调用

2. 以静态方式(用::操作符)调用的方法中$this的取值是由调用时的上下文决定的!而不是定义他的类!!

例如以下的代码:

<&#63;php 
class TestClass1 
{ 
  public $normal_v = 'normal_v from TestClass1'; 
  public static $STATIC_V = 'STATIC_V from TestClass1'; 
  public function test_func1() 
  { 
    echo $this->normal_v.'<br />'.self::$STATIC_V; 
  } 
} 
class TestClass2 
{ 
  public $normal_v = 'normal_v from TestClass2'; 
  public static $STATIC_V = 'STATIC_V from TestClass2'; 
  public function test_func2() 
  { 
    TestClass1::test_func1(); 
  } 
} 
$t2 = new TestClass2(); 
$t2->test_func2(); 

Nach dem Login kopieren

这段代码是输出会是什么呢,我原以为会是normal_v from TestClass1
STATIC_V from TestClass1,测试发现其实我错了,正确的输出是:

normal_v from TestClass2
STATIC_V from TestClass1

说明:test_func1()虽然是在TestClass1中定义的,但却是在TestClass2中调用的,其内部的$this变量则是由TestClass2决定的!

其实这两个类的关系应该属于"双向关联".

感兴趣的朋友可以测试运行本文实例,相信会有新的收获!

php中对于静态方法的问题

self::是代表在本类里调用静态方法get();因为在静态方法里面只能调静态方法,不能调用实例方法,如果调用实例方法的话那就用this,
 

php的静态方法调用问题

PHP目前两种方法都可以用,静态类,只是说方便调用,不用初始化类。
但如果你的写法不对的话。静态类就失去了静态调用的能力。
举个错误的例子。

class Cat {
}
class Hypnotic_Cat extends Cat
{
public $string = "The cat was hypnotized.\r\n";
function Hypnotic_Cat()
{
}
public static function hypnotize()
{
echo self::$string;
}
}
Hypnotic_Cat::hypnotize();
$hypnotic_cat = new Hypnotic_Cat();
$hypnotic_cat->hypnotize();
?>

正确的例子

class Cat {
}
class Hypnotic_Cat extends Cat
{
public static $string = "The cat was hypnotized.\r\n";
function Hypnotic_Cat()
{
}
public static function hypnotize()
{
echo self::$string;
}
}
Hypnotic_Cat::hypnotize();
$hypnotic_cat = new Hypnotic_Cat();
$hypnotic_cat->hypnotize();
?>
 

Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Empfehlungen
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!