Home > Backend Development > PHP Tutorial > php中的类、对象

php中的类、对象

WBOY
Release: 2016-06-23 13:12:54
Original
1109 people have browsed it

类是我们队一组对象的描述

在php里,每个类的定义都以关键字class开头,后面跟着类名,紧接着一对花括号,里面包含有类成员和方法的定义。如下代码所示

class person{    public $name;    public $gender;    public function say(){        echo $this->name."is ".$this->gender;    }}
Copy after login

接下来就可以产生这个类的实例:

$student = new person();$student->name="Tome";$student->gender= "male";$student->say();$teacher= new person();$teacher->name="kati";$teacher->gender= "female";$teacher->say();
Copy after login

这段代码则实例化了person类,产生了一个student对象和teacher对象的实例。实际上也就是从抽象到具体的过程。

对类和对象的一些理解:

  • 类定义了一系列的属性和方法,并提供了实际的操作细节,这些方法可以用来对属性进行加工。
  • 对象含有类属性的具体值,这就是类的实例化。正是由于属性的不同,才能区分不同的对象。在上面例子里,由于student和teacher的性别和姓名不一样,才得以区分开二人。
  • 类与对象的关系类似一种服务于被服务、加工与被加工的关系,具体而言,就如同原材料与流水线的关系。只需要在对象上调用类中所存在的方法,就可以对类的属性进行加工,并且展现其功能。

打印student对象

print_r((array)$student);var_dump($student);
Copy after login

序列化对象

$str = serialize($student);echo $str;file_put_contents('store.txt',$str);输出结果:0:6:"person":2:{s:4:"name";s:3:"Tom";s:6:"gender";s:4:"mail";}
Copy after login

反序列化对象

$str = file_get_contents('store.txt');$student = unserialize($str);$student->say();
Copy after login

转载自:http://www.9958.pw/post/php_class

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template