PHP Classes: when to use :: vs. ->?

后端 未结 7 2195
暗喜
暗喜 2020-12-04 19:36

I understand that there are two ways to access a PHP class - \"::\" and \"->\". Sometime one seems to work for me, while the other doesn\'t, and I don\'t understand why.

7条回答
  •  不思量自难忘°
    2020-12-04 20:13

    :: is used to access a class static property. And -> is used to access a class instance ( Object's ) property.

    Consider this Product class that has two functions for retrieving product details. One function getProductDetails belongs to the instance of a class, while the other getProductDetailsStatic belongs to the class only.

    class Product {
      protected $product_id;
    
      public function __construct($product_id) {
        $this->product_id = $product_id;
      }
    
      public function getProductDetails() {
         $sql = "select * from products where product_id= $this->product_id ";
         return Database::execute($sql);
      }
    
      public static function getProductDetailsStatic($product_id) {
         $sql = "select * from products where product_id= $product_id ";
         return Database::execute($sql);
      }
    }
    

    Let's Get Products:

    $product = new Product('129033'); // passing product id to constructor
    var_dump( $product->getProductDetails() ); // would get me product details
    
    var_dump( Product::getProductDetailsStatic('129033') ); // would also get me product details
    

    When to you use Static properties?

    Consider this class that may not require a instantiation:

    class Helper {
      static function bin2hex($string = '') {
      }
      static function encryptData($data = '') {
      }
      static function string2Url($string = '') {
      }
      static function generateRandomString() {
      }
    }
    

提交回复
热议问题