search
HomeBackend DevelopmentPHP Tutorialphp:兄弟连之面向对象版图形计算器1

php:兄弟连之面向对象版图形计算器1

Jun 23, 2016 pm 01:56 PM
phpband of brothersgraphicscalculatorobject-oriented

 以前看细说PHP的时候就想做这个,但是一直没什么时间,这次总算忙里偷闲搞了代码量比较多的工程。

首先,文档结构,都在一个目录下就好了,我的就如下。


一开始,进入index.php文件。

<title>图形计算器(面向对象)</title><meta http-equiv="Content-Type" content="text/html;charset=utf-8">	<center>		<h1 id="图形-面积-周长-计算器">			图形(面积 周长)计算器)			</h1>				<a href="index.php?action=rect">矩形</a><!-- action 是动作提交 -->				|| 				<a href="index.php?action=triangle">三角形</a>				||				<a href="index.php?action=circle">圆形</a>				<hr>		</center>        <?php error_reporting ( E_ALL & ~ E_NOTICE );								//PHP遇到不认识的类就会调用该方法自动加载								function __autoload($className) 								{									include strtolower ( $className ) . ".class.php";								}																/*								 *因为遇到Form类不认识,所以自动加载form.class.php 								 *   */								echo new Form ('index.php');																if (isset ( $_POST ["sub"] )) {																		echo new Result ();								}																?>  

做了这么几件事

1.可以通过$GET_[“action”]方法和$_REQUEST ["action"]方法得到传入的参数是rect, triangle还是circle。

2.通过echo new Form("index.php")和echo new Result()方法加载了form.class.php和result.class.php这两个类

3.通过echo调用了这两个类的__toString方法


接下来程序加载form.class.php这个文件

<?phpclass Form {	private $action;	private $shape;	function __construct($action = "") {		$this->action = $action;		/* var_dump($this->action); */		$this->shape = isset ( $_REQUEST ["action"] ) ? $_REQUEST ["action"] : "rect";		/* var_dump($this->shape); */	}		/* __toString() 方法用于一个类被当成字符串时应怎样回应。例如 echo $obj; 应该显示些什么。此方法必须返回一个字符串 	 * 	 * 在此输出一个表单	 * 	 * */	function __toString() {		$form = '
'; switch ($this->shape) { case "rect" : $form .= $this->getRect (); break; case "triangle" : $form .= $this->getTriangle (); break; case "circle" : $form .= $this->getcircle (); break; default : $form .= '请选择一个形状'; } $form .= ''; $form .= '
'; return $form; } private function getRect() { $input = '请输入|矩形|的长和宽:

'; $input .= '宽度:
'; $input .= '高度:
'; $input .= ''; return $input; } private function getTriangle() { $input = '请输入|三角形|的三边:

'; $input = '请输入|三角形|的三边:

'; $input .= '第一边:
'; $input .= '第二边:
'; $input .= '第三边:
'; $input .= ''; return $input; } private function getCircle() { $input = '请输入|圆形|的半径:

'; $input .= '半径:
'; $input .= ''; return $input; }}?>
这个php做了另外一件事,就是根据$_REQUEST ["action"]或者GET_["action"]加载了不同类型形状的表单。

然后,一旦你按下计算按钮,接下来就转到了加载result.class.php这个文件

<?php class Result{              private $shape;              /*                * 根据form.class.php里传过来的$post['action']方法接受参数               *  */             function __construct(){                               switch($_POST['action']){                                    case 'rect':                                                      $this->shape=new Rect();                                          break;                                                       case 'triangle':                                                   $this->shape=new Triangle();                                       break;                                                        case 'circle':                                                   $this->shape=new Circle();                                       break;//没有break会导致default的执行                             default:                                                           $this->shape=false;                                 }            }                function __toString(){                                  if($this->shape){                                            $result=$this->shape->shapeName.'的周长'.$this->shape->perimeter().'<br>';                             $result.=$this->shape->shapeName.'的面积'.$this->shape->area().'<br>';                             return $result; }                                        else{                             return'没有这个形状';                                }}}   ?>

这个文件做了一件事,就是分流,根据$_POST["action"]传过来的值看,执行那一个类文件

下一篇讲各个类文件含义。

Statement
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
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment