Using the object-oriented graphing calculator

Source: Internet
Author: User
This example may not be practical, but it basically outlines the three characteristics of object-oriented: inheritance, encapsulation, polymorphism. The main functions of this example are:

    1. Allows users to select different types of graphics;
    2. Enter its related properties for the selected graphic;
    3. Calculates the perimeter and area of the graph based on the attributes you enter.

The effect is as follows:


      1. Part A is written directly in index.php, and clicking on the corresponding graphic sends a $_get["shape" to its own page, using the auto-load class.
      2. Part B is output by form.class.php, where variable functions are used, and different functions are called with the values of $_get["shape" to determine the input portion of a form with different shapes.
      3. The c part is output by result.class.php. Declares an abstract class that computes the calculation of area and perimeter in an abstract class in rect,triangle,circle, embodying inheritance, encapsulation and polymorphism, using new $_get["shape"] () to instantiate the object of the corresponding graphic, and then invoking the method in that object. Returns the perimeter and area.

Areas needing improvement:

    1. This example is only intended as a demonstration class for several features, and does not filter the user's input, may cause injection attacks, not applicable to actual production applications. The actual application should filter the user's input to prevent malicious attacks.
    2. The page layout is not optimized with DIV+CSS and the interface is not very friendly. You can optimize the layout and improve the user experience.

The index.php code is as follows:

1 2 3         
 4 5 6         7         

Graphics Perimeter Area Calculator

8 9RectangularTenTriangle OneCircular A - - Php the/*Auto Load Class*/ -function__autoload ($className){ -include(Strtolower($className).'. Class.php '); - } + -/* +1. A new Form object is found without the definition of the form class, and the class name form is passed to the auto-load class's function parameter for automatic loading of classes. A2.echo A reference to an object that invokes the __tostring method of the object to return a string, and echo outputs the string returned by the object . atthis outputs a form waiting for the user's input. -*/ -EchoNewForm ("index.php"); - -/*If the user clicks the Submit button, the result class is automatically loaded and the output*/ -if(isset($_post["Sub"])){ inEchoNewresult (); - } to?> + - the

The form.class.php code is as follows:

 Php2/*3Project: Object-oriented graphing calculator4file:form.class.php5Description: Different forms for different graphic outputs6*/7classform{8Private$formAction=NULL;//Save the file for the response form9Private$shape=NULL;//Save the shape of a graphicTen One/* A@param string $action object that initializes the passed-in parameter, which file represents the page of the response -*/ -function__construct ($action= ""){ the$this->formaction =$action;//Save the incoming parameters to the $formaction; -$this->shape =isset($_get["Shape"]) ?$_get["Shape"]: "rect";//gets a graphics category from a variable passed from a form, such as a rectangle that is not passed, by default -                } -function__tostring () { +$form= ''; - -return$form; -                } in//a private method that returns the string of the input portion of the rectangle form; -PrivatefunctionGetRect () { to//content entered after form submission continues to appear, preventing it from disappearing +$formheight=isset($_post[' Height ']) ?$_post[' Height ']:NULL; -$formwidth=isset($_post[' width ']) ?$_post[' Width ']:NULL; the$input= '

Please enter the length and width of the rectangle

'; *$input. = ' Height of rectangle:

'; $$input. = ' Width of rectangle:
';Panax Notoginsengreturn$input; - } the//the string that returns the input portion of the Triangle entry Form +PrivatefunctionGettriangle () { A//continue to display after form submission to prevent it from disappearing the$formside 1=isset($_post[' Side1 ']) ?$_post[' Side1 ']:NULL; +$formside 2=isset($_post[' Side2 ']) ?$_post[' Side2 ']:NULL; -$formside 3=isset($_post[' Side3 ']) ?$_post[' Side3 ']:NULL; $$input= '

Please enter three sides of the triangle

'; $$input. = ' Side length 1:

'; -$input. = ' Side length 2:

'; -$input. = ' Side length 3:
'; thereturn$input; - }Wuyi//string that returns the input portion of a circular form thePrivatefunctiongetcircle () { -$formradius=isset($_post[' radius ']) ?$_post[' Radius ']:NULL;//content continues to appear after the input form is submitted to prevent it from disappearing Wu$input= '

Please enter radius

'; -$input. = ' Radius:
'; Aboutreturn$input; $ } - } -

The result.class.php code is as follows:

 Php2classresult{3Private$shape=NULL;45//instantiate a corresponding object by using a variable passed by get, and return a reference to an object;6function__construct () {7$this->shape =New$_get["Shape"]();8        }9//invokes the properties and methods of the object, returning the perimeter and areaTenfunction__tostring () { One$result=$this->shape->shapename. ' Perimeter is '.$this->shape->perimeter (). '
'; A$result.=$this->shape->shapename. ' The area is '.$this->shape->area (). '
'; -return$result; - } the}

The abstract class shape.class.php code is as follows:

 Php2/*3Project: Object-oriented graphing calculator4file:shape.class.php5Description: Abstract class, defining two abstract methods area () and perimeter (), and defining methods validate validating input values6*/7Abstractclassshape{8 Public$shapeName;//shape name;9AbstractfunctionArea ();//abstract class area (), allowing subclasses to implement, manifesting polymorphismTenAbstractfunctionPerimeter ();//abstract class perimeter (); One A/* -@param mixed $value accept form input values -@param string $message hint message prefix the@param boolean return value, Success is true, failure is false -*/ -protectedfunctionValidate$value,$message= "Input Value"){ -if($value< 0 | |$value==NULL|| !Is_numeric($value)){ +$message=$this->shapename.$message; -Echo''.$message.' Must be a positive number
'; +returnFALSE; A } atElse -returnTRUE; - } -}

The subclass triangle.class.php code is as follows:

 Php2/**3Project: Object-oriented graphing calculator4file:triangle.class.php5Description: Inherits the abstract class shape, calculates and returns the perimeter and area of the triangle6*/7classTriangleextendsshape{8Private$side 1= 0;//side length 1;9Private$side 2= 0;//side length 2;TenPrivate$side 3= 0;//side length 3; One A/* -constructor: Validate the form variable reasonably, by initializing three edge lengths -*/ thefunction__construct () { -$this->shapename = "triangle";//naming Graphics - -//Use the parent class's method validate check whether the input is a positive number +if($this->validate ($_post["Side1"], "side length 1") &$this->validate ($_post["Side2"], "side length 2") &$this->validate ($_post["Side3"], "Edge length 3")){ - +//use private methods to verify that both sides are greater than the third side Aif($this->validatesum ($_post["Side1"],$_post["Side2"],$_post["Side3"])){ at$this->side1 =$_post["Side1"];//If the three sides are initialized by verification; -$this->side2 =$_post["Side2"]; -$this->side3 =$_post["Side3"]; -                        } -Else{ -Echo' on both sides and to be greater than the third side '; inExit(); -                        } to                } +Else{ -Exit(); the                } *        } $/*use the Helen formula to calculate the area and return the result*/Panax NotoginsengfunctionArea () { -$s= ($_post["Side1"] +$_post["Side2"] +$_post["Side3"]) /2; thereturnsqrt($s* ($s-$_post["Side1"]) * ($s-$_post["Side2"]) * ($s-$_post["Side3"])); +        } A/*calculate and return perimeter*/ thefunctionperimeter () { +return$_post["Side1"] +$_post["Side2"] +$_post["Side3"]; -        } $/*calculates whether the triangle is greater than the third side, returns True, no returns false*/ $PrivatefunctionValidatesum ($side 1,$side 2,$side 3){ -if(($side 1+$side 2) >$side 3&& ($side 1+$side 3) >$side 2&& ($side 2+$side 3) >$side 1) -returnTRUE; theElse -returnFALSE;Wuyi        } the}

The subclass circle.class.php code is as follows:

 Php2/*3Project: Object-oriented graphing calculator4file:circle.class.php5Description: Receive form values, return perimeter and area6*/7classCircleextendsshape{8Private$radius;//radius of the circle9Ten//Initialize the name of the circle, check the validity of the input and initialize the radius Onefunction__construct () { A$this->shapename = "Round"; -if($this->validate ($_post["Radius"], "radius")) -$this->radius =$_post["Radius"]; the        } -//returns the area of a circle -functionArea () { -return3.14 *$this->radius *$this-radius; +        } -//returns the perimeter of a circle +functionperimeter () { Areturn3.14 * 2 *$this-radius; at        } -}

The subclass rect.class.php code is as follows:

 Php2/*3Project: Object-oriented graphing calculator4file:rect.class.php5descrition: Declares a rectangle data, realizes the shape abstract class calculates the circumference and the area the method, returns the rectangle circumference and the area6*/7classRectextendsshape{8Private$width;//width of Rectangle9Private$height;//height of the rectangleTen One//Use the Validate method of the parent class to verify the legitimacy of the input by initializing the width and height Afunction__construct () { -$this->shapename = "Rectangle"; -if($this->validate ($_post["width"], "width") &&$this->validate ($_post["Height"], "height")){ the$this->width =$_post["width"]; -$this->height =$_post["Height"]; -        } -        } +//return Area -functionArea () { +return$this->width *$this-height; A        } at//return perimeter -functionperimeter () { -return2 * ($this->width +$this-height); -        } -}


1. This article only suitable for the experiment, is not suitable for the real application, if causes the undesirable consequence, I am not responsible.

2. This article is the original blog, can be freely reproduced in the personal platform, but need to indicate the source, attached link, otherwise considered misappropriation. Strictly prohibited for commercial use, if necessary, contact me to pay royalties, authorized to use the rear.

The above describes the use of object-oriented graphics calculator, including aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.