【问题标题】:PHP: Declare the type of an argument as Class (like Java)PHP:将参数的类型声明为 Class(如 Java)
【发布时间】:2023-03-19 18:41:02
【问题描述】:

我们可以在java中将参数的类型指定为ClassClass<?>Class<SomeClass>Class<? extends SomeClass>。另外,我们知道PHP has added type declaration capability (were also known as type hints in PHP 5)。那么有一种方法可以在 PHP 中将 function 的参数类型声明为 Class(如 Java)吗?

例如(在 PHP 中):

function f(Class<string> $clazz) { ... }  // ???

【问题讨论】:

  • 您想要一个通用的“类”类型还是特定的类?
  • @Scuzzy。两个都。但如果一个不可能,我想要另一个。每个都有其重要性。
  • 看起来这可能是相关的:wiki.php.net/rfc/generics——据我所知,PHP 不提供您目前需要的这种类型的功能。您可以省略类型声明,这并不理想,但这样做可以让您拥有不同的实例,其中一些使用 string,一些使用 FooClass 等等

标签: php function class type-hinting type-declaration


【解决方案1】:

如你所说,这在 PHP 中称为type hinting

来自 PHP 文档的示例:

<?php
// An example class
class MyClass
{
    /**
     * A test function
     *
     * First parameter must be an object of type OtherClass
     */
    public function test(OtherClass $otherclass) {
        echo $otherclass->var;
    }


    /**
     * Another test function
     *
     * First parameter must be an array
     */
    public function test_array(array $input_array) {
        print_r($input_array);
    }

    /**
     * First parameter must be iterator
     */
    public function test_interface(Traversable $iterator) {
        echo get_class($iterator);
    }

    /**
     * First parameter must be callable
     */
    public function test_callable(callable $callback, $data) {
        call_user_func($callback, $data);
    }
}

// Another example class
class OtherClass {
    public $var = 'Hello World';
}
?>

您的问题中真正重要的部分是这个函数,其中OtherClass 指定参数必须是OtherClass 的实例,否则,PHP 将抛出错误。

<?php
    /**
     * A test function
     *
     * First parameter must be an object of type OtherClass
     */
    public function test(OtherClass $otherclass) {
        echo $otherclass->var;
    }
?>

【讨论】:

  • 我不想要OtherClass 类型的变量(参数)!我想要一个类型为 OtherClass 的参数;可以在 Java 中声明,例如:Class&lt;OtherClass&gt; var.
猜你喜欢
  • 2012-02-16
  • 1970-01-01
  • 2019-02-26
  • 1970-01-01
  • 1970-01-01
  • 2015-02-20
  • 1970-01-01
  • 2017-09-10
相关资源
最近更新 更多