Simple Calculator with Php oop
In this article I will be showing you how to create a simple calculator using objected oriented programming in php.
I am going to be making use of 3 files.
index.html : The home page where the users interface would be created. No functionality would be added here, its just going to be pure html code.
class.php: Remember we are doing this with oop, so we are going to be making use of classes, methods and all this would be done in this file.
action.php: Finally we would be creating an action file where the action of the form created in the index page would be pointing and this is where the main action takes place as we would be including our class.php file here.
I took out time to explain simply what this files are and what you should expect in each file.
In the index.html file, I would create a simple html form with no styling.It would include 3 fields and a submit button. Note that our form method will be POST and the form action would be action.php.
In the class.php file, we would first start by creating our class, which would later be instantiated in our action.php file.
After creating the class, we would declare or list all the properties we would use as public so they could easily be accessed in other files, we could also make them private since we will later call them in a public function.
After declaring or listing them, we can now go ahead to call them in our public function construct .
We can now go ahead to create a public function calculate() to switch each case .Remember we are dealing with four cases:
Addition
Subtraction
Multiplication
Division
once we are done we can now go ahead to then get the values passed through the form via the post method. Remeber to include your file class.php in this file .
then instantiate the class Calc() and input the properties.
$data = new Calc($num1, $sign, $num2);
we would now do the final thing by calling the function.
echo $data->Calculate();
Remeber to place all your codes in the php tag if needed so it can run without bug.
Conclusion
This is just how to create a simple calculator using php oop and basic html code. If you face any challenge running the code make sure you drop a comment and it would be fixed.
Follow me on twitter. Enjoy!