Saturday, January 16, 2010

Simple OOP Form with PHP

Let's face it, as a developer, you WILL have to do some playing with PHP. It's just a matter of time and if you can't stand the language, you're gonna have to just deal with it. As PHP is still one of the most widely used server-side languages today, it's juts best to learn the language, and learn it the right way.

Now, when I say the right way, I mean, by using programming best practices as stated in my last blog about UML, MVC and OOP. This blog is about OOP in general and why it is the best and cleanest way to program your applications.

Below is a very simple example of PHP OOP and forms:

The PHP the class:
<?php
class HelloClass
{
public function sayHello($obj)
{
echo $say_hello = "Hello there " . $this->hello_name;
return say_hello;
}
}
?>

The HTML:
<form action="" name="hello_form" method="post">
Enter your name:<br/>
<input type="text" name="hello_name" value="" /><br/>
<input type="submit" name="hello_submit" value="Say Hello"/>
<input type="hidden" name="hello" value="true"/>
</form>

Define the objects:
<?php
$obj = new HelloClass;
$obj->hello_name = $_POST['hello_name'];
$obj->hello = $_POST['hello'];
$obj->sayHello($obj);
?>

The results:
Hello there "Name that was entered"
Ex: Hello there Pete

I know the code might be a bit messy on Blogger but feel free to download this example here.

- Pete

No comments: