Home > Backend Development > PHP Problem > What is the use of php static methods?

What is the use of php static methods?

(*-*)浩
Release: 2023-02-24 06:22:02
Original
2971 people have browsed it

What is the use of php static methods?

Static method

(1) Static methods cannot access ordinary properties in this class, because those properties belong to an object, but they can be accessed Static properties;

(2) To access static methods or properties from the current class (not a subclass), you can use the self keyword, self points to the current class, just like $this points to the current object;

(3) Static methods cannot be called in objects. Static methods and attributes are also called class methods and class attributes, so the pseudo variable $this cannot be used in objects.

Advantages of static methods: (Recommended learning: PHP programming from entry to proficiency)

(1) It can be used anywhere in the code Use (assuming the class can be accessed);

(2) Each instance of the class can access the static properties defined in the class, and can use static properties to set values, which can be used by all objects of the class ;

(3) Static properties or methods can be accessed without an instance object.

<?php
$pdo = new PDO(&#39;mysql:host=localhost;dbname=mydb&#39;,&#39;root&#39;);  // 生成一个 PDO(PHP Data Object) 对象
class ShopProduct{
    private $title;             // 属性也称为成员变量,用来存放对象之间互不相同的数据
    private $producerMainName;  // 所有的属性都设置为 private,不允许外部直接访问这些属性,然后提供方法来取得需要的值
    private $producerFirstName;
    protected $price;           // 阻止外面直接访问该属性,可以被子类访问
    private $discount = 0;
    private $id = 0;

    // 创建对象时,构造方法会被自动调用,构造方法可以确保必要的属性设置,并完成任何需要准备的工作
    public function __construct($title,$mainName,$firstName,$price){
        $this->title = $title;      // 使用伪变量$this给每个变量赋值
        $this->producerMainName = $mainName;
        $this->producerFirstName = $firstName;
        $this->price = $price;
    }

    /**
     * @return mixed 这种只返回属性值的方法称为“访问方法”,也称为 getter 和 setter
     */
    public function getProducerFirstName()
    {
        return $this->producerFirstName;
    }

    /**
     * @return mixed 获取 姓 的访问方法
     */
    public function getProducerMainName()
    {
        return $this->producerMainName;
    }

    /**
     * @param $num 打折的价格
     */
    public function setDiscount($num)
    {
        $this->discount = $num;
    }

    /**
     * @return int 折扣的访问方法
     */
    public function getDiscount()
    {
        return $this->discount;
    }

    /**
     * @return mixed Book名或CD名的访问方法
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * @return mixed 折扣后的价格
     */
    public function getPrice()
    {
        return ($this->price - $this->discount);
    }

    /**
     * @return string 作者
     */
    public function getProducer(){  // 方法让对象执行任务
        return $this->producerMainName .&#39; &#39;. $this->producerFirstName;
    }

    /**
     * @return string 发票的摘要信息
     */
    public function getSummaryLine()
    {
        $base = "{$this->title} ( {$this->producerMainName},{$this->producerFirstName}) ";
        return $base;
    }

    /**
     * @param $id id 的访问方法, setter
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    // 根据查询数据的数据类型,返回特定类型的 ShopProduct 对象,这个方法没有使用任何实例的属性和方法,因此把它定义为一个静态方法(static),只要有一个有效的 PDO 对象,就可以在程序的任何地方调用这个方法。这个方法就像工厂一样,可以接受原始数据产生特定类型的对象。
    public static function getInstance($id,PDO $pdo)
    {
        $stmt = $pdo -> prepare("SELECT * FROM products WHERE id=?");
        $stmt -> execute(array($id));
        $row = $stmt -> fetch();
        if(empty($row)){
            return null;
        }
        switch($row[&#39;type&#39;])
        {
            case &#39;book&#39; :
                $product = new BookProduct($row[&#39;title&#39;],$row[&#39;first_name&#39;],$row[&#39;main_name&#39;],$row[&#39;price&#39;],$row[&#39;num_pages&#39;]);
            break;
            case &#39;cd&#39; :
                $product = new CdProduct($row[&#39;title&#39;],$row[&#39;first_name&#39;],$row[&#39;main_name&#39;],$row[&#39;price&#39;],$row[&#39;play_length&#39;]);
            break;
            default :
                $product = new ShopProduct($row[&#39;title&#39;],$row[&#39;first_name&#39;],$row[&#39;main_name&#39;],$row[&#39;price&#39;]);
            break;
        }
        $product -> setId($row[&#39;id&#39;]);
        $product -> setDiscount($row[&#39;discount&#39;]);
        return $product;
    }
}

// 若派生类没有定义构造方法,则它在实例化是会自动调用父类的构造方法。子类默认继承父类所有的 public 和 protected 方法,但不继承 private 方法和属性
class BookProduct extends ShopProduct
{
    private $numPages;

    // 每个子类在设置自己的属性前调用父类的构造方法,基类现在仅知道自己的数据,子类一般是父类的特列,应该避免告诉父类任何关于子类的消息。
    public function __construct($title,$mainName,$firstName,$price,$numPages)
    {
        // parent 关键字可以在任何复写父类方法的方法中使用,通过在当前对象中调用父类的方法来拓展父类的功能 , 要应用一个类而不是对象的方法,使用 :: 而不是 ->
        parent::__construct($title,$mainName,$firstName,$price);
        $this -> numPages = $numPages;
    }

    /**
     * @param $numPages 书的页数
     * @return mixed    总页数
     */
    public function getNumberOfPages()
    {
        return $this->numPages;
    }

    /**
     *  子类(派生类)可以覆盖和修改父类(基类或超类)的功能
     * @return string Book发票的摘要信息
     */
    public function getSummaryLine()
    {
        $base = parent::getSummaryLine();
        $base .= "page count - {$this->numPages}";
        return $base;
    }
}

class CdProduct extends ShopProduct
{
    private $playLength;

    public function __construct($title,$mainName,$firstName,$price,$playLength)
    {
        parent::__construct($title,$mainName,$firstName,$price);
        $this -> playLength = $playLength;
    }

    /**
     * @return int 播放时间
     */
    public function getPlayLength()
    {
        return $this -> playLength;
    }

    /**
     * @return string CD发票的摘要信息
     */
    public function getSummaryLine()
    {
        $base = parent::getSummaryLine();
        $base .= "playing time - {$this->playLength}";
        return $base;
    }
}

$product = ShopProduct::getInstance(1,$pdo);     // 该静态方法根据传入 id 的不同生成特定类型的对象
if($product){
    print "author : {$product -> getProducer()} </br>";              // author :Lun Xun
    print "summary line: {$product -> getSummaryLine()}</br>";      // summary line: Kong Yiji ( Xun,Lun) page count - 200
}
Copy after login

Attached (pictures of sql files and data):

What is the use of php static methods?

What is the use of php static methods?

The above is the detailed content of What is the use of php static methods?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template