Home php教程 php手册 php5类型约束学习笔记

php5类型约束学习笔记

May 25, 2016 pm 04:49 PM
php5 study notes type constraint

php是一种弱类型的编程语言,在php程序中,变量的数据类型可以随着其值的不同而自动发生改变,php也不会对变量的数据类型进行强制检查或约束.

我们可以参考下面一个简单的代码示例:

<?php
class Person {
}
$a = 1; //此时,$a为整数类型型(Integer)
var_dump($a);
$a = 1.0; //此时,$a为浮点类型(Float)
var_dump($a);
$a = &#39;CodePlayer&#39;; //此时,$a为字符串类型(String)
var_dump($a);
$a = array(
    &#39;CodePlayer&#39; => &#39;http://www.phprm.com&#39;
); //此时,$a为数组类型(Array)
var_dump($a);
$a = new Person(); //此时,$a为Person对象类型(Object)
var_dump($a);
$a = mysql_connect(&#39;localhost&#39;, &#39;username&#39;, &#39;password&#39;); //此时,$a为资源类型(Resource)
var_dump($a);
?>
Copy after login

php弱数据类型的特点使得php使用起来显得简单而灵活,不过,这同样也是一把达摩克利斯之剑,也正是由于php弱数据类型的特点,在编写php程序代码时,开发人员更需要时刻注意变量数据类型的变化,尤其是变量作为函数的参数进行传递时,更需要注意这一点,毕竟,大多数的函数参数都只期望是某种特定的数据类型,例如,在下面的例子中,函数sayHi()期望接收的参数类型是Person对象类型,但是,由于php并不是强类型的语言,也不会强制检查变量的类型,因此我们可以向函数中传递任意类型的参数,从而导致程序报错或逻辑出现异常,实例代码如下:

<?php
class Person {
    public $name = &#39;CodePlayer&#39;;
    public $age = 3;
}
function sayHi($person) {
    echo "Hello! My name is $person->name. I&#39;m $person->age years old.";
}
$p = &#39;张三&#39;;
sayHi($p); //不是期望的Person对象类型,将出现Notice级别错误信息,程序仍然继续运行
echo &#39;Suffix&#39;; //仍然会输出该文本信息
?>
Copy after login

从php 5开始,我们就可以使用新增的类型约束机制来对函数参数的部分数据类型进行类型约束。同样以上面的代码为例,我们可以在编写sayHi()函数时要求传递进来的参数必须是Person对象类型,否则引发致命错误(Fatal Error),并终止当前页面脚本的运行。要使用php的类型约束机制非常简单,我们只需要在函数声明的参数变量前添加指定的类型名称即可。当我们调用该函数时,php会强制检查函数的参数是否为指定的类型,如果不是指定的类型则引发致命错误,代码如下:

<?php
class Person {
    public $name = &#39;CodePlayer&#39;;
    public $age = 3;
}
function sayHi(Person $person) {
    echo "Hello! My name is $person->name. I&#39;m $person->age years old.";
}
$person = &#39;张三&#39;;
sayHi($person); //不是期望的Person对象类型,引发Fatal Error致命错误,程序终止运行
echo &#39;Suffix&#39;; //不会输出该文本信息,程序终止运行
?>
Copy after login

值得注意的是,在php 5中,目前只有对象、接口、数组、callable类型的参数变量才能使用类型约束(数组类型是从php 5.1版本开始支持的,callable类型是从php 5.4版本开始支持的)。

注意:如果使用类型约束的参数变量没有声明其默认值为null,调用该函数时就不能给对应的参数变量传递null值,否则同样也会报错。

类型约束不能用于标量类型如 int 或 string。Traits 也不允许。

Example #1 类型约束示例代码如下:

<?php 
//如下面的类 
class MyClass 
{ 
/** 
 * 测试函数 
 * 第一个参数必须为 OtherClass 类的一个对象 
 */ 
public function test(OtherClass $otherclass) { 
echo $otherclass->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 = &#39;Hello World&#39;; 
} 
?>
Copy after login

函数调用的参数与定义的参数类型不一致时,会抛出一个可捕获的致命错误,代码如下:

<?php
// 两个类的对象
$myclass = new MyClass;
$otherclass = new OtherClass;
// 致命错误:第一个参数必须是 OtherClass 类的一个对象
$myclass->test(&#39;hello&#39;);
// 致命错误:第一个参数必须为 OtherClass 类的一个实例
$foo = new stdClass;
$myclass->test($foo);
// 致命错误:第一个参数不能为 null
$myclass->test(null);
// 正确:输出 Hello World
$myclass->test($otherclass);
// 致命错误:第一个参数必须为数组
$myclass->test_array(&#39;a string&#39;);
// 正确:输出数组
$myclass->test_array(array(
    &#39;a&#39;,
    &#39;b&#39;,
    &#39;c&#39;
));
// 正确:输出 ArrayObject
$myclass->test_interface(new ArrayObject(array()));
// 正确:输出 int(1)
$myclass->test_callable(&#39;var_dump&#39;, 1);
?>
Copy after login

类型约束不只是用在类的成员函数里, 也能使用在函数里, 代码如下:'

<?php
// 如下面的类
class MyClass {
    public $var = &#39;Hello World&#39;;
}
/** 
 * 测试函数
 * 第一个参数必须是 MyClass 类的一个对象
 */
function MyFunction(MyClass $foo) {
    echo $foo->var;
}
// 正确
$myclass = new MyClass;
MyFunction($myclass);
?>
Copy after login

类型约束允许 NULL 值:

<?php
/* 接受 NULL 值 */
function test(stdClass $obj = NULL) {
}
test(NULL);
test(new stdClass);
?>
Copy after login


文章链接:

随便收藏,请保留本文地址!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the difference between php5 and php8 What is the difference between php5 and php8 Sep 25, 2023 pm 01:34 PM

The differences between php5 and php8 are in terms of performance, language structure, type system, error handling, asynchronous programming, standard library functions and security. Detailed introduction: 1. Performance improvement. Compared with PHP5, PHP8 has a huge improvement in performance. PHP8 introduces a JIT compiler, which can compile and optimize some high-frequency execution codes, thereby improving the running speed; 2. Improved language structure, PHP8 introduces some new language structures and functions. PHP8 supports named parameters, allowing developers to pass parameter names instead of parameter order, etc.

How to change network type to private or public in Windows 11 How to change network type to private or public in Windows 11 Aug 24, 2023 pm 12:37 PM

Setting up a wireless network is common, but choosing or changing the network type can be confusing, especially if you don't know the consequences. If you're looking for advice on how to change the network type from public to private or vice versa in Windows 11, read on for some helpful information. What are the different network profiles in Windows 11? Windows 11 comes with a number of network profiles, which are essentially sets of settings that can be used to configure various network connections. This is useful if you have multiple connections at home or office so you don't have to set it all up every time you connect to a new network. Private and public network profiles are two common types in Windows 11, but generally

Implementing dynamic arrays in Python: from beginner to proficient Implementing dynamic arrays in Python: from beginner to proficient Apr 21, 2023 pm 12:04 PM

Part 1 Let’s talk about the nature of Python sequence types. In this blog, let’s talk about Python’s various “sequence” classes and the three built-in commonly used data structures – list, tuple and character. The nature of the string class (str). I don’t know if you have noticed it, but these classes have an obvious commonality. They can be used to save multiple data elements. The most important function is: each class supports subscript (index) access to the elements of the sequence, such as using SyntaxSeq[i]​. In fact, each of the above classes is represented by a simple data structure such as an array. However, readers familiar with Python may know that these three data structures have some differences: for example, tuples and strings cannot be modified, while lists can.

How to create a video matrix account? What types of matrix accounts do it have? How to create a video matrix account? What types of matrix accounts do it have? Mar 21, 2024 pm 04:57 PM

With the popularity of short video platforms, video matrix account marketing has become an emerging marketing method. By creating and managing multiple accounts on different platforms, businesses and individuals can achieve goals such as brand promotion, fan growth, and product sales. This article will discuss how to effectively use video matrix accounts and introduce different types of video matrix accounts. 1. How to create a video matrix account? To make a good video matrix account, you need to follow the following steps: First, you must clarify what the goal of your video matrix account is, whether it is for brand communication, fan growth or product sales. Having clear goals helps develop strategies accordingly. 2. Choose a platform: Choose an appropriate short video platform based on your target audience. The current mainstream short video platforms include Douyin, Kuaishou, Huoshan Video, etc.

How to change port 80 in php5 How to change port 80 in php5 Jul 24, 2023 pm 04:57 PM

How to change port 80 in php5: 1. Edit the port number in the Apache server configuration file; 2. Edit the PHP configuration file to ensure that PHP works on the new port; 3. Restart the Apache server, and the PHP application will start running on the new port. run on the port.

PHP study notes: data structures and algorithms PHP study notes: data structures and algorithms Oct 09, 2023 pm 11:54 PM

PHP study notes: Overview of data structures and algorithms: Data structures and algorithms are two very important concepts in computer science. They are the key to solving problems and optimizing code performance. In PHP programming, we often need to use various data structures to store and operate data, and we also need to use algorithms to implement various functions. This article will introduce some commonly used data structures and algorithms, and provide corresponding PHP code examples. 1. Linear structure array (Array) Array is one of the most commonly used data structures and can be used to store ordered data.

Learn database functions in Go language and implement addition, deletion, modification and query operations of PostgreSQL data Learn database functions in Go language and implement addition, deletion, modification and query operations of PostgreSQL data Jul 31, 2023 pm 12:54 PM

Learn the database functions in the Go language and implement the addition, deletion, modification, and query operations of PostgreSQL data. In modern software development, the database is an indispensable part. As a powerful programming language, Go language provides a wealth of database operation functions and toolkits, which can easily implement addition, deletion, modification and query operations of the database. This article will introduce how to learn database functions in Go language and use PostgreSQL database for actual operations. Step 1: Install the database driver in Go language for each database

What is the type of return value of Golang function? What is the type of return value of Golang function? Apr 13, 2024 pm 05:42 PM

Go functions can return multiple values ​​of different types. The return value type is specified in the function signature and returned through the return statement. For example, a function can return an integer and a string: funcgetDetails()(int,string). In practice, a function that calculates the area of ​​a circle can return the area and an optional error: funccircleArea(radiusfloat64)(float64,error). Note: If the function signature does not specify a type, a null value is returned; it is recommended to use a return statement with an explicit type declaration to improve readability.

See all articles