Php 简明教程

PHP - Compound Types

PHP 中的数据类型可以是“标量类型”或“复合类型”。整数、浮点数、布尔值和字符串类型为标量类型,而数组和对象类型归类为复合类型。复合类型中的单个变量可以存储多种类型的值。

Data types in PHP can be of "scalar type" or "compound type". Integer, float, Boolean and string types are scalar types, whereas array and object types are classified as compound types. Values of more than one types can be stored together in a single variable of a compound type.

在 PHP 中,对象和数组是两种复合数据类型。

In PHP, objects and arrays are the two compound data types.

  1. An array is an ordered collection of elements of other data types, not necessarily of the same type.

  2. An object is an instance of either a built-in or a user defined class, consisting of properties and methods.

Arrays in PHP

数组是一种数据结构,其中一个变量存储了一个或多个数据值。PHP 中的数组是有序映射,它将值与键关联。

An array is a data structure that stores one or more data values in a single variable. An array in PHP is an ordered map that associates the values to their keys.

  1. There are two ways to declare an array in PHP. One is to use the built-in array() function, and the other is to put the array elements inside square brackets.

  2. An array which is a collection of only values is called an indexed array. Each value is identified by a positional index staring from 0.

  3. If the array is a collection of key-value pairs, it is called as an associative array. The key component of the pair can be a number or a string, whereas the value part can be of any type.

The array() Function in PHP

内置 array() 函数使用提供给它的参数并返回数组类型对象。一个或多个以逗号分隔的参数是数组中的元素。

The built-in array() function uses the parameters given to it and returns an object of array type. One or more comma-separated parameters are the elements in the array.

array(mixed ...$values): array

括号中的每个值可以是单个值(可能是数字、字符串、任何对象,甚至另一个数组),或键值对。键与其值之间的关联由“⇒”符号表示。

Each value in the parenthesis may be either a singular value (it may be a number, string, any object or even another array), or a key-value pair. The association between the key and its value is denoted by the "⇒" symbol.

Example

请查看以下示例:

Take a look at this following example −

$arr1 = array(10, "asd", 1.55, true);

$arr2 = array("one"=>1, "two"=>2, "three"=>3);

$arr3 = array(
   array(10, 20, 30),
   array("Ten", "Twenty", "Thirty"),
   array("physics"=>70, "chemistry"=>80, "maths"=>90)
);

Using Square Brackets [ ]

除了 array() 函数之外,还可以将以逗号分隔的数组元素置于方括号内以声明数组对象。在这种情况下,元素也可以是单个值、字符串或另一个数组。

Instead of the array() function, the comma-separated array elements may also be put inside the square brackets to declare an array object. In this case too, the elements may be singular values or a string or another array.

$arr1 = [10, "asd", 1.55, true];

$arr2 = ["one"=>1, "two"=>2, "three"=>3];

$arr3 = [
   [10, 20, 30],
   ["Ten", "Twenty", "Thirty"],
   ["physics"=>70, "chemistry"=>80, "maths"=>90]
];

Accessing Array Elements

要从给定数组访问任何元素,可以使用 array[key] 语法。对于索引数组,将索引置于方括号内,因为索引本身就是键。

To access any element from a given array, you can use the array[key] syntax. For an indexed array, put the index inside the square bracket, as the index itself is anyway the key.

<?php
   $arr1 = [10, 20, 30];
   $arr2 = array("one"=>1, "two"=>2, "three"=>3);

   var_dump($arr1[1]);
   var_dump($arr2["two"]);
?>

它将生成以下 output

It will produce the following output

int(20)
int(2)

Array Traversal in PHP

还可以使用 foreach 循环来迭代索引数组。

You can also use the foreach loop to iterate through an indexed array.

<?php
   $arr1 = [10, 20, 30, 40, 50];
   foreach ($arr1 as $val){
      echo "$val\n";
   }
?>

它将生成以下 output

It will produce the following output

10
20
30
40
50

请注意,PHP 在内部将索引数组视为关联数组,其中索引被视为键。此事实可以通过数组的 var_dump() 输出得到验证。

Note that PHP internally treats the indexed array as an associative array, with the index being treated as the key. This fact can be verified by the var_dump() output of the array.

我们可以使用 foreach 语法将索引数组的每个元素解包为键和值变量 −

We can unpack each element of the indexed array in the key and value variables with the foreach syntax −

<?php
   $arr1 = [10, 20, 30, 40, 50];
   foreach ($arr1 as $key => $val){
      echo "arr1[$key] = $val" . "\n";
   }
?>

它将生成以下 output

It will produce the following output

arr1[0] = 10
arr1[1] = 20
arr1[2] = 30
arr1[3] = 40
arr1[4] = 50

foreach 循环还用于遍历关联数组,尽管任何其他类型的循环也可以通过某种操作使用。

The foreach loop is also used for iterating through an associative array, although any other type of loop can also be used with some maneuver.

让我们看一下 foreach 循环实现,每个 k-v 对在两个变量中解包。

Let us look at the foreach loop implementation, with each k-v pair unpacked in two variables.

<?php
   $capitals = array(
      "Maharashtra"=>"Mumbai",
      "Telangana"=>"Hyderabad",
      "UP"=>"Lucknow",
      "Tamilnadu"=>"Chennai"
   );

   foreach ($capitals as $k=>$v) {
      echo "Capital of $k is $v" . "\n";
   }
?>

它将生成以下 output

It will produce the following output

Capital of Maharashtra is Mumbai
Capital of Telangana is Hyderabad
Capital of UP is Lucknow
Capital of Tamilnadu is Chennai

Objects in PHP

在 PHP 中,对象是一种复合数据类型。它是内置或用户定义类的实例。下面是一个简单的 PHP 类 −

In PHP, an object is a compound data type. It is an instance of either a built in or user defined class. Given below is a simple PHP class −

class SayHello {
   function hello() {
      echo "Hello World";
   }
}

要声明类的对象,我们需要使用 new 操作符。

To declare an object of a class, we need to use the new operator.

$obj=new SayHello;

我们现在可以调用它的方法 −

We can now call its method −

<?php
   class SayHello {
      function hello() {
         echo "Hello World". PHP_EOL;
      }
   }

   $obj=new SayHello;
   var_dump(gettype($obj));
   $obj->hello();
?>

它将生成以下 output

It will produce the following output

string(6) "object"
Hello World

stdClass

PHP 提供 stdClass 作为一个通用的空类,它可用于动态添加属性和转换。stdClass 的对象开始时为 null。我们可以动态地向其中添加属性。

PHP provides stdClass as a generic empty class which is useful for adding properties dynamically and casting. An object of stdClass is null to begin with. We can add properties to it dynamically.

<?php
   $obj=new stdClass;
   $obj->name="Deepak";
   $obj->age=21;
   $obj->marks=75;

   print_r($obj);
?>

它将生成以下 output

It will produce the following output

stdClass Object (
   [name] => Deepak
   [age] => 21
   [marks] => 75
)

Array to Object Conversion in PHP

PHP 中的数组可以按如下方式强制转换成对象 −

An array in PHP can be typecast to an object as follows −

<?php
   $arr=array("name"=>"Deepak", "age"=>21, "marks"=>75);
   $obj=(object)$arr;

   print_r($obj);
?>

它将生成以下 output

It will produce the following output

stdClass Object (
   [name] => Deepak
   [age] => 21
   [marks] => 75
)

Object to Array Conversion in PHP

相反,对象可以强制转换成数组。请看以下示例 −

Conversely, an object can be cast to an array. Take a look at the following example −

<?php
   $obj=new stdClass;
   $obj->name="Deepak";
   $obj->age=21;
   $obj->marks=75;

   $arr=(array)$obj;
   print_r($arr);
?>

它将生成以下 output

It will produce the following output

Array
(
   [name] => Deepak
   [age] => 21
   [marks] => 75
)

Scalar Type to Object Type Conversion in PHP

任何标量类型的变量也可以通过类型转换转换成对象。标量变量的值将成为对象标量属性的值。

A variable of any scalar type can also be converted to an object by type casting. The value of the scalar variable becomes the value of the object’s scalar property.

<?php
   $name="Deepak";
   $age=21;
   $percent=75.50;

   $obj1=(object)$name;
   print_r($obj1);

   $obj2=(object)$age;
   print_r($obj2);

   $obj3=(object)$percent;
   print_r($obj3);
?>

它将生成以下 output

It will produce the following output

stdClass Object
(
   [scalar] => Deepak
)
stdClass Object
(
   [scalar] => 21
)
stdClass Object
(
   [scalar] => 75.5
)