PHP:静态和非静态函数和对象

PHP:静态和非静态函数和对象,php,static,Php,Static,这些对象调用之间有什么区别 非静态: $var = new Object; $var->function(); $var = User::function(); 静态: $var = new Object; $var->function(); $var = User::function(); 而且在类中为什么要对函数使用static属性 例如: static public function doSomething(){ ...code... } 静态方法和成员属于类

这些对象调用之间有什么区别

非静态:

$var = new Object;
$var->function();
$var = User::function();
静态:

$var = new Object;
$var->function();
$var = User::function();
而且在
类中
为什么要对函数使用static属性

例如:

static public function doSomething(){
    ...code...
}

静态方法和成员属于类本身,而不属于类的实例。

根据定义,静态函数不能也不依赖于类的任何实例属性。也就是说,它们不需要类的实例来执行(因此可以像您所展示的那样执行,而无需先创建实例)。从某种意义上说,这意味着函数不(也永远不需要)依赖于类的成员或方法(公共或私有)。

静态函数或字段不依赖于初始化;因此,静态。

差异在变量范围内。想象一下你有:

class Student{
    public $age;
    static $generation = 2006;

   public function readPublic(){
       return $this->age;  
   }

   public static function readStatic(){
       return $this->age;         // case 1
       return $student1->age;    // case 2 
       return self::$generation;    // case 3 

   }
}

$student1 = new Student();
Student::readStatic();
class Example {

    // property declaration
    public $value = "The text in the property";

    // method declaration
    public function displayValue() {
        echo $this->value;
    }

    static function displayText() {
        echo "The text from the static function";
    }
}


$instance = new Example();
$instance->displayValue();

$instance->displayText();

// Example::displayValue();         // Direct call to a non static function not allowed

Example::displayText();
  • 静态函数不能知道$this是什么,因为它是静态的。如果有$this,它应该属于$student1,而不是Student

  • 它也不知道什么是$student1

  • 它确实适用于案例3,因为它是一个属于类的静态变量,不同于前2个属于必须实例化的对象


  • 关于静态函数的问题不断出现


    根据定义,静态函数不能也不依赖于类的任何实例属性。也就是说,它们不需要类的实例来执行(因此可以执行)。 从某种意义上说,这意味着函数不(也永远不需要)依赖于类的成员或方法(public或private)

    class Example {
    
        // property declaration
        public $value = "The text in the property";
    
        // method declaration
        public function displayValue() {
            echo $this->value;
        }
    
        static function displayText() {
            echo "The text from the static function";
        }
    }
    
    
    $instance = new Example();
    $instance->displayValue();
    
    $instance->displayText();
    
    // Example::displayValue();         // Direct call to a non static function not allowed
    
    Example::displayText();
    

    @马里奥。有点苛刻。也许cirk确实读过手册,并没有完全理解这个概念。向其他程序员征求一些意见似乎是公平的。@Ben。也许太苛刻了。但我不想在没有评论或只是一个RTFM链接的情况下投反对票。我猜他确实在某个地方读过,但他征求了“第二意见”这里。如果他这么说的话,哪一个更合适。将静态函数放在类中而不是放在单独的functions.php文件中有什么意义?@billmarky这不是必需的,但它至少可以帮助您将函数组织到相关的文件中。对我来说,使用诸如
    User::someFunction();
    而不是
    Function::someUserFunction;
    当然比
    someFunction();