繁体   English   中英

静态方法与非静态方法

[英]static method vs non-static method

以下是静态方法和非静态方法的php类代码示例。

范例1:

class A{
    //None Static method
    function foo(){
        if (isset($this)) {
            echo '$this is defined (';
            echo get_class($this);
            echo ")<br>";
        } else {
            echo "\$this is not defined.<br>";
        }
    }
 }

 $a = new A();
 $a->foo();
 A::foo();

 //result
 $this is defined (A)
 $this is not defined.

范例2:

class A{
    //Static Method
    static function foo(){
        if (isset($this)) {
            echo '$this is defined (';
            echo get_class($this);
            echo ")<br>\n";
        } else {
            echo "\$this is not defined.<br>\n";
        }
    }
 }

 $a = new A();
 $a->foo();
 A::foo();

 //result
 $this is not defined.
 $this is not defined.

我试图找出这两个类之间的区别。

正如我们在非静态方法的结果中看到的那样,定义了“ $ this”。

但是另一方面,即使静态方法都被实例化,也没有定义静态方法的结果。

我想知道为什么自从将它们都实例化后它们会有不同的结果?

您能给我启发一下这些代码上发生了什么。

我们继续之前:请进入的总是你指定对象的属性和方法的可见性/可访问的习惯中。 而不是写作

function foo()
{//php 4 style method
}

写:

public function foo()
{
    //this'll be public
}
protected function bar()
{
    //protected, if this class is extended, I'm free to use this method
}
private function foobar()
{
    //only for inner workings of this object
}

首先,您的第一个示例A::foo将触发通知(静态地调用非静态方法总是这样做)。
其次,在第二个示例中,当调用A::foo() ,PHP不会创建即时实例,当您调用$a->foo()时,它也不会在实例的上下文中调用该方法。 $a->foo() (还会发出BTW通知)。 静态从本质上讲是全局函数,因为在内部,PHP对象不过是C struct ,而方法只是具有指向该结构的指针的函数。 至少这就是要点, 更多细节在这里

静态属性或方法的主要区别(如果使用得当,则有好处)是它们在所有实例之间共享并且可以全局访问:

class Foo
{
    private static $bar = null;
    public function __construct($val = 1)
    {
        self::$bar = $val;
    }
    public function getBar()
    {
        return self::$bar;
    }
}
$foo = new Foo(123);
$foo->getBar();//returns 123
$bar = new Foo('new value for static');
$foo->getBar();//returns 'new value for static'

如您所见,不能在每个实例上设置静态属性$bar ,如果更改了其值,则该更改将应用​​于所有实例。
如果$bar是公共的,那么您甚至都不需要实例来更改各处的属性:

class Bar
{
    public $nonStatic = null;
    public static $bar = null;
    public function __construct($val = 1)
    {
        $this->nonStatic = $val;
    }
}
$foo = new Bar(123);
$bar = new Bar('foo');
echo $foo->nonStatic, ' != ', $bar->nonStatic;//echoes "123 != foo"
Bar::$bar = 'And the static?';
echo $foo::$bar,' === ', $bar::$bar;// echoes 'And the static? === And the static?'

查看工厂模式,并(纯粹提供信息)也查看Singleton模式。 就Singleton模式而言:此外,google为什么使用它。 IoC,DI,SOLID是您很快会遇到的缩写。 了解它们的含义,并弄清楚为什么他们(以自己的方式)是选择Singletons的主要原因

有时您需要使用一种方法,但是却不想调用类,因为类中的某些函数会自动调用,例如__construct,__ destruct,...(魔术方法)。

叫课:

$a = new A();
$a->foo();

不要调用class :(只需运行foo()函数)

A::foo();

http://php.net/manual/en/language.oop5.magic.php

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM