【静态和非静态方法】调用静态和非静态方法【原创】

在学习PHP面向对象的时候,遇到了一些问题:
class Test1
{
public function test() {
echo "test1的test普通方法";
}
}
在Test1类中,定义了一个test方法。一般呢,想要调用test方法的话,是通过实例化一个对象来调用test方法的。比如:
aaa.php:
<?php
//正常的方式访问普通方法test 
class Test1
{
public function test()
{
echo "test1的test普通方法";
}
}
 
$new = new Test1();
$new->test();
但是呢,由于失误写错了,并没有实例化而是通过访问静态方法来调用test方法,比如:
bbb.php:
<?php
//访问静态方法的方式访问普通方法test 
class Test1
{
public function test()
{
echo "test1的test普通方法";
}
}
 
Test1::test();
然后发现是可以正常调用test方法的。然后通过查阅资料发现:
也就是说,上面的Test1::test();其实会被转化为:
$new = new Test1();
$new->test();

这样呢,就有另外一个问题了,如果是一个静态方法,然后通过访问普通方法的方式通过实例化一个对象来访问这个静态方法是否可行呢?比如:
class Test2
{
static function test() {
echo "test2的test静态方法";
}
}
对于Test2类里面的静态方法test的调用呢,一般呢,是通过直接Test2::test();来调用的。比如:
ccc.php:
<?php
//访问静态方法的方式访问普通方法test 
class Test1
{
static function test()
{
echo "test1的test静态方法";
}
}
 
Test1::test();
使用访问普通方法的方式去调用:
ddd.php:
<?php
//通过实例化的方式访问静态方法test 
class Test2
{
static function test()
{
echo "test2的test静态方法";
}
}
 
$new = new Test2();
$new -> test();
发现,也是可以正常显示出来的。

总结:虽然两者都可以互相调用,但是最好还是建议规范化。

posted @ 2016-05-22 16:07  Newman·Li  阅读(240)  评论(0编辑  收藏  举报