[php classes and objects] type constraints

不言
Release: 2023-03-24 07:38:01
Original
1288 people have browsed it

The content of this article is about [php classes and objects] type constraints, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

Type constraints

PHP 5 can use type constraints.

The parameters of the function can be specified as:

  • Object (specify the name of the class in the function prototype)

  • Interface

  • Array (PHP 5.1)

  • callable (PHP 5.4)

If using NULL as The default value of the parameter, then NULL can still be used as the actual parameter when calling the function.

If a class or interface specifies a type constraint, so do all its subclasses or implementations.

Type constraints cannot be used for scalar types such as int or string. Traits are not allowed either.

Example #1 类型约束示例 var; } /** * 另一个测试函数 * 第一个参数必须为数组 */ public function test_array(array $input_array) { print_r($input_array); } } /** * 第一个参数必须为递归类型 */ public function test_interface(Traversable $iterator) { echo get_class($iterator); } /** * 第一个参数必须为回调类型 */ public function test_callable(callable $callback, $data) { call_user_func($callback, $data); } }// OtherClass 类定义class OtherClass { public $var = 'Hello World'; } ?>
Copy after login

Related recommendations:

[php classes and objects] object copy

[php classes and objects]magic method

【php classes and objects】Traversal

The above is the detailed content of [php classes and objects] type constraints. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!