【问题标题】:Type hinting in phpphp中的类型提示
【发布时间】:2013-02-17 01:54:38
【问题描述】:

所以我找到了这个例子,我正在学习php oop,我想问一下addProduct方法中的参数ShopProduct是什么意思以及它有什么作用?

abstract class ShopProductWriter {
    protected $products = array();
    public function addProduct( ShopProduct $shopProduct ) {
        $this->products[]=$shopProduct;
    }
}

【问题讨论】:

  • PHP 称它为 Type Hinting
  • 请不要引用作业。这既不必要又有害。

标签: php oop arguments type-hinting


【解决方案1】:

让我们逐行看:

abstract class ShopProductWriter {

声明一个名为ShopProductWriterabstract 类。 abstract 类不能被实例化(你永远不能拥有ShopProductWriter 的实例。)为了使用这个类,你必须创建一个扩展ShopProductWriter 的类。 http://php.net/manual/en/language.oop5.abstract.php

protected $products = array();

创建一个名为$products 的类变量,它是一个数组。这个变量的可见性是protected。这意味着 $products 只能使用 this 运算符从类上下文中访问。此外,$this->products 将可用于扩展 ShopProductWriter 的所有类。 http://php.net/manual/en/language.oop5.visibility.phphttp://php.net/manual/en/language.oop5.basic.php

public function addProduct( ShopProduct $shopProduct ) {

定义了一个名为addProduct 的可见函数public,该函数可以在任何扩展ShopProductWriter 的类实例的类上下文之外调用。此函数采用单个参数,该参数必须是 ShopProduct 的实例或扩展 ShopProduct 的子类 (“如果将类或接口指定为类型提示,则也允许其所有子类或实现。”参见 @ 987654324@).

$childInstance = new ChildCLassExtendingShopProductWriter();
$childInstance->addProduct($IAmAShopProductInstance);

最后,

$this->products[]=$shopProduct;

该函数将传递给 addProduct 函数的任何实例添加到类数组products

【讨论】:

    【解决方案2】:

    表示$shopProduct必须是ShopProduct类的实例

    但请注意,类型提示仅适用于对象、数组和接口。您不能为字符串做类型提示,例如

    不能

    function wontWork(string $string) {}

    【讨论】:

    • 谢谢 :) 我想我明白了使用类型提示的原因
    【解决方案3】:

    它将给定的产品添加到对象存储的产品列表中。

    【讨论】:

      【解决方案4】:

      ShopProductWriter 是一个抽象类。 $products 是一个受保护的变量,其中存储了 array addProduct 是一个函数,其中对象存储的产品列表

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-21
        • 2013-06-06
        • 2013-07-18
        • 2017-04-24
        • 2015-12-30
        • 2016-09-12
        • 2010-12-20
        • 2023-03-22
        相关资源
        最近更新 更多