PHP入门教程之面向对象基本概念实例分析
本文实例讲述了PHP面向对象基本概念。分享给大家供大家参考,具体如下:
Demo1.php
<?php //怎样去创建一个类格式:修饰符class类名{} //我们去创建一个电脑的类,这类可以创建出对象(生产出电脑) classComputer{//类名第一个字母大写 } //创建一台电脑出来,也就是对象的声明 //格式:变量=new类名(); //newCompuer()表示实例化的过程(意思是创建一个对象) //$compuer1=newCompuer()这个过程就是把实例化对象的地址给$compuer1 //$compuer1我们就可以称作为对象的应用 $computer1=newComputer();//这是我们创建的第一台电脑 $computer2=$computer1;//这是我们创建的第二台电脑 var_dump($computer1); echo'<br/>'; var_dump($computer1); ?>
Demo2.php
<?php header('Content-Type:text/html;charset=utf-8;'); //classComputer{ ////字段成员的声明格式:修饰符变量名[=xxx]; //public$_name='联想';//public表示共有,类外可以访问 //public$_model='i7'; //} ////创建一个对象,生产出一台电脑->表示指向 //$computer1=newComputer(); //echo$computer1->_name; //$computer1->_name='dell'; //echo$computer1->_name; classComputer{ //字段成员的声明格式:修饰符变量名[=xxx]; public$_name;//public表示共有,类外可以访问 public$_model; } //创建一个对象,生产出一台电脑->表示指向 $computer1=newComputer(); //给成员字段赋值 $computer1->_name='联想'; //取值 echo$computer1->_name; ?>
Demo3.php
<?php header('Content-Type:text/html;charset=utf-8;'); classComputer{ public$_name;//public表示共有,类外可以访问 public$_model; //创建方法的格式:修饰符function方法名(){} //如果不加修饰符,默认就是public function_run(){ echo'我是运行的方法'; } } //创建一个对象,生产出一台电脑->表示指向 $computer1=newComputer(); $computer1->_run(); ?>
Demo4.php
<?php header('Content-Type:text/html;charset=utf-8;'); //classComputer{ ////字段成员的声明格式:修饰符变量名[=xxx]; //public$_name='联想';//public表示共有,类外可以访问 //public$_model='i7'; //} ////创建一个对象,生产出一台电脑->表示指向 //$computer1=newComputer(); //echo$computer1->_name; //$computer1->_name='dell'; //echo$computer1->_name; classComputer{ //字段成员的声明格式:修饰符变量名[=xxx]; public$_name;//public表示共有,类外可以访问 public$_model; } //创建一个对象,生产出一台电脑->表示指向 $computer1=newComputer(); //给成员字段赋值 $computer1->_name='联想'; //取值 //echo$computer1->_name; $computer2=$computer1; echo$computer2->_name; ?>
Demo5.php
<?php header('Content-Type:text/html;charset=utf-8;'); classComputer{ public$_name;//public表示共有,类外可以访问 public$_model; //创建方法的格式:修饰符function方法名(){} //如果不加修饰符,默认就是public function_run($_who){ echo$_who.'是运行的方法'; } } //创建一个对象,生产出一台电脑->表示指向 $computer1=newComputer(); $computer1->_run('一站式建网站'); ?>
Demo6.php
<?php header('Content-Type:text/html;charset=utf-8;'); classComputer{ //创建一个构造方法 publicfunctionComputer(){ echo'我是构造方法'; } } //只要实例化,就可以运行构造方法 //$computer=newComputer(); newComputer(); ?>
Demo7.php
<?php header('Content-Type:text/html;charset=utf-8;'); classComputer{ //创建一个构造方法 publicfunction__construct(){ echo'我是比较先进的构造方法'; } } //只要实例化,就可以运行构造方法 //$computer=newComputer(); newComputer(); ?>
Demo8.php
<?php header('Content-Type:text/html;charset=utf-8;'); classComputer{ //创建一个构造方法 publicfunction__construct(){ echo'我是比较先进的构造方法'; } //析构方法 publicfunction__destruct(){ echo'我是析构方法'; } //普通方法 publicfunction_run(){ echo'我是普通方法'; } } //只要实例化,就可以运行构造方法 $computer=newComputer(); $computer->_run(); ?>
更多关于PHP相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。