代码如下 | 复制代码 |
class child $parent = new parent('hispanic'); |
php教程中是通过类来完成信息封装的,在php中定义类的语法是:
class class_name // 在面向对象编程类中,习惯上类的第一个字符为大写,并且必须符合变量的命名规则。
{
//函数与变量的集合
}
?>
在定义类时你可以按自已的喜好的格式进行定义,但最好能保持一种标准,这样开发起来会更有效些。
数据成员在类中使用"var"声明来定义,在给数据成员赋值之前,它们是没有类型的。一个数据成员可以是一个整数,一个数组,一个相关数组(associative array)或者是一个对象。
下面是一个类定义的实际例子:
代码如下 | 复制代码 |
class student { var $str_name; //姓名 var $str_sex; //性别 var $int_id; //学号 var $int_english; //英语成绩 var $int_maths; //数学成绩 } ?> |
这是一个很普通定义类的简单例子,用于显示学生的学习成绩,类名为student,student类包涵了一个学生的基本属性:姓名、性别、学号、英语成绩和数学成绩。
function我们称之为在类中被定义的函数,在函数中访问类成员变量时,你应该使用$this->var_name,其中var_name 指的是类中被声明的变量,否则对一个函数来说,它只能是局部变量。 我们先定义一个input()的函数,用来给实例中的对象赋以初值:
代码如下 | 复制代码 |
function input ( $name, $sex, $id, $englis, $maths) { $this->str_name=$name; $this->str_sex =$sex; $this->int_id =$id; $this->int_englis=$english; $this->int_maths=$maths; } |
现在我们再定义一个叫“showinfo()”的函数,用于打印学生的基本情况:
代码如下 | 复制代码 |
function showinfo() //定义showinfo()函数 ”); ”); ”); ”); ”); |
而定义好的类则必须使用new关键词来生成对象:
$a_student=new student;
例如我们要为一个名为$wing的对象创建实例,并进行赋值,可以使用下面的代码:
$wing =new student; //用new关键词来生成对象
$wing ->input (“wing”,”男”,33,95,87);
//分别输入wing的姓名、性别、学号、英语成绩、数学成绩,其中姓名和性别是字符型变量,所以需要用双引号,其它为数值型变量则不需要。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor