Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Help With OOP

Featured Replies

Hi All, I have decided to learn more about OOP PHP 5, I have just done a small form validation class

can you tell me how to improve it, although it works i am sure its not the best way to go about it

 

 

<?php
class validate
{
public function validate()
{
 foreach($_POST as $key)
{
if(empty($key))
{
return false;
}
else {
return true;
}
}

}
}
?>
<form action="" method="post">
<input name="name" type="text" />
<input name="number" type="text" />
<input type="submit" name="sub" value="submit" />
</form>
<?php
if(isset($_POST['sub']))
{
$name=$_POST['name'];
$number=$_POST['number'];
$val=new validate;
$val->validate;
if($name==true && $number==true)
{
echo "both fields were filled in";
}
if($name==false || $number==false)
{
echo "Sorry Validation failed";
}
}
?>

 

Thank you

Edited by ELITE

That's not really OO, it's a class but it's not OO.

 

For a start, its way too basic to demonstrate OOP practices and as an example it kind of breaks the purpose of OOP.

 

 

In a class you have class properties. i.e. a user class would have a set of properties pertaining to the users data specification. In the case of a class that offers utility functions these might be a bit low on the ground; if anything exists at all.

 

Then you have methods for each piece of functionality the class offers; for example a posting class - used for parsing forum posts, could have a bunch of utility methods for handling the content processing of forum posts or comments; such as BBCode or Emoticons.

 

The class should offer functions that are relevant to it's score and you shouldn't have inline HTML code in classes; it kind of defeats the object of using OO (to create easy to maintain, modular, independant and reusable code); UI output should be passed over to a templating or view class.

 

 

ETA:

 

The two points I'm really getting at is, that it's far too basic to be useful or feedback on and I would say the pouring of HTML code and break out within the class is fundamentally against OOP.

Edited by FizixRichard

Your class is a a little weak in the OOP department. for example if you wanted a class that was used form sending form mail it may look a little like this

 

<?php
class FormMail{
protected $to = "localhost@localhost.com";
protected $from = "localhost@localhost.com";
protected $message = "";
protected $CharSet = "";
protected $type = "text/plain";
protected $header = array();
//Our constructor
public function __construct($to,$from,$message,$CharSet,$type){
$this->SetTo($to);
$this->SetFrom($from);
$this->SetChar($CharSet);
$this->SetType($type);
$this->SetMessage($message);
}
//Protected methods
protected function SetTo($to){
$this->to = $to;
}
protected function SetFrom($from){
$this->from = $from;
}
protected function SetMessage($message){
$this->message = $message;
}
protected function SetChar($charset){
$this->CharSet = $charset;
}
protected function SetType($type){
$this->type = $type
//Public methods
public function SendMail(){
//Send your mail
}
}
?>

 

this class is not complete by no means but gives you a rough idea then it can be used like this

 

$mail = new FormMail("yoursite@yourdomain.com","My Website","My Message","utf-8","text/html");
$mail->SendMail();

Edited by webdesigner93

  • Author

Thanks it my weakest part of programing so thought i would learn the basics

Your class is a a little weak in the OOP department. for example if you wanted a class that was used form sending form mail it may look a little like this

 

<?php
class FormMail{
protected $to = "localhost@localhost.com";
protected $from = "localhost@localhost.com";
protected $message = "";
protected $CharSet = "";
protected $type = "text/plain";
protected $header = array();
//Our constructor
public function __construct($to,$from,$message,$CharSet,$type){
$this->SetTo($to);
$this->SetFrom($from);
$this->SetChar($CharSet);
$this->SetType($type);
$this->SetMessage($message);
}
//Protected methods
protected function SetTo($to){
$this->to = $to;
}
protected function SetFrom($from){
$this->from = $from;
}
protected function SetMessage($message){
$this->message = $message;
}
protected function SetChar($charset){
$this->CharSet = $charset;
}
protected function SetType($type){
$this->type = $type
//Public methods
public function SendMail(){
//Send your mail
}
}
?>

 

this class is not complete by no means but gives you a rough idea then it can be used like this

 

$mail = new FormMail("yoursite@yourdomain.com","My Website","My Message","utf-8","text/html");
$mail->SendMail();

 

you also could go further and extend your FormMail class with a validation class

 

class FormMail extends Validation

If your plan is to learn the basics, I would recommend creating a basic but complete class that takes advantage of the fundamental processes of OOP. webdesigner93 highlights the basics with his/her class.

 

However, I would recommend starting with a class that has a more useful data definition. Something like a user class that holds data that is used elsewhere and is interacted with in a number of ways.

 

As from a class like that you can start with a very basic definition; like:

 

Class properties that define a user

Setting the properties through methods and returning the properties through methods

 

Then braching out to provide more utility, such as hooking up registration, interfacing with the DB and creating login systems; where several classes interact.

 

So you could have a procedural script which calls upon classes that handle data and utility. How to instantiate the classes, access and set the data, and tie in functionality; while following OOP principals. You'll learn more and it will be more beneficial.

 

Then when you feel a little more comfortable, maybe even looking at very basic MVC architectures which actually put OOP into a better context and show how OO applications should be structured.

Edited by FizixRichard

Seriously if you're new to OO then get a book and learn the basic concepts behind it... It won't take long the theory will ground in you in how you should be developing and why it can lead to better code..

 

Once you've read the book then come back and ask specific questions.... You won't learn OO from just messing around with PHP

 

Beyond learning about OO principles you then have the massive world of design patterns and all that lovley stuff...

 

Good luck, it'll be an exciting journey....

 

Zee

I have attached some form validation classes for you to look at. Its something I wrote a few years ago and never got round to finishing!

 

<html>
   <head>
    <title>Form demo</title>
    <style>
        .error { border: 1px solid red; }
        dt { float: left; }
        dt.required { background: transparent url("images/asterisk.png") no-repeat top right; padding-right:10px; }
        dd { margin: 0em 0em 1em 11em;}
    </style>
   </head>
   <body>
<?php

error_reporting(-1);
ini_set('display_errors', 'on');
ini_set('display_startup_errors', 'on');

function autoLoader($className){
   $path = str_replace('_', '/', $className);
   include_once '../library/'.$path.'.php';
}

spl_autoload_register('autoLoader');

$form = new Fluid_Form();
$form->addProcessor(new Fluid_Form_Processor_Email());

$name = new Fluid_Form_Element_Input_Text('name');
$name->setLabel('Your name')
 ->addFilter(new Fluid_Filter_Alnum())
 ->setRequired(true, true)
 ->addValidator(new Fluid_Validate_String(array('maxLength'=>32, 'minLength'=>3)));

$password = new Fluid_Form_Element_Input_Password('password');
$password->setLabel('Password')
	 ->setRequired(true, true)
	 ->addValidator(new Fluid_Validate_String(array('maxLength'=>32, 'minLength'=>3)));     

$email = new Fluid_Form_Element_Input_Text('email');
$email->setLabel('Email Address')
 ->setRequired(true)
 ->addValidator(new Fluid_Validate_String(array('maxLength'=>128, 'minLength'=>))
 ->addValidator(new Fluid_Validate_Email);

$select = new Fluid_Form_Element_Select('team');
$select->setLabel('Favourite Team')
   ->setMultiOptions(array('rangers', 'celtic', 'hibs', 'hearts', 'motherwell', 'aberdeen'));


$submit = new Fluid_Form_Element_Input_Submit('btnSubmit', array('label'=>'Send Enquiry'));

$form->addElements(array($name, $password, $email, $select, $submit));

if($_SERVER['REQUEST_METHOD'] === 'POST') {
   if($form->isValid($_POST)) {
    echo "Form is valid.";
    $form->process();
   } else {
    echo $form;
   }
} else {
   echo $form;    
}
?>
   </body>
</html>

 

Would render something like...

post-19630-0-25675500-1350422232_thumb.png

 

Obviously you wouldn't have it in an HTML file, you would make your own form My_Form extend Form but its just an example. Let me know if you need any more info.

Fluid.zip

  • Author
I have attached some form validation classes for you to look at. Its something I wrote a few years ago and never got round to finishing!

 

Thank you very much

  • Author

I have ordered a couple of books on OOP but i am still trying a few things, I came up with this for working VAT out at 20%

<?php
class tax
{
 var $tax;
 function add($tax)
 {
 $addedTax = $this->tax=number_format($tax/100*20, 2, '.', '');
 return $addedTax;
 }
 function price($tax)
 {
   $addedTax = $this->tax=number_format($tax/100*20, 2, '.', '');
  $price=number_format($tax-$addedTax,2,'.','');
  return $price;
 }
}
?>
<form action="" method="post">
<input name="vat" type="text" />
<input type="submit" name="tax" value="submit" />
</form>
<?php
if(isset($_POST['tax']))
{
$tax=number_format($_POST['vat'],2 ,'.',''); 
$get=new tax;
echo "Price Without VAT £" . $get->price($tax). "<br />";
echo "Total Price INC £$tax <br />";
echo "Vat £" . $get->add($tax); 
}
?>

 

how bad is this

 

Thank you

In terms of coding, it's still not an ideal class.

 

There's no constructor, no access modifiers, no getters or setters, etc etc. Also, you're using the "var" keyword which is deprecated and not needed and your methods aren't being used properly.

 

That's at a quick glance.

 

Edit: I realized I didn't really give a good explanation of what I meant when I said the "your methods aren't being used properly". Some users above me wrote about the the proper use of properties and methods and how they relate to the class.

Edited by Pete Prosper

I have ordered a couple of books on OOP but i am still trying a few things, I came up with this for working VAT out at 20%

<?php
class tax
{
var $tax;
function add($tax)
{
$addedTax = $this->tax=number_format($tax/100*20, 2, '.', '');
return $addedTax;
}
function price($tax)
{
$addedTax = $this->tax=number_format($tax/100*20, 2, '.', '');
$price=number_format($tax-$addedTax,2,'.','');
return $price;
}
}
?>
<form action="" method="post">
<input name="vat" type="text" />
<input type="submit" name="tax" value="submit" />
</form>
<?php
if(isset($_POST['tax']))
{
$tax=number_format($_POST['vat'],2 ,'.','');
$get=new tax;
echo "Price Without VAT £" . $get->price($tax). "<br />";
echo "Total Price INC £$tax <br />";
echo "Vat £" . $get->add($tax);
}
?>

 

how bad is this

 

Thank you

 

theres not a whole bunch you can do with a simple class like yours but heres a little better version

 

<?php
class tax
{
private $tax;
private $price;
private $addedTax;
/**
*Our construct
**/
public function __construct($tax){
$this->tax = $tax;
}
/**
*Add the tax
**/
public function add()
{
$this->addedTax = number_format($this->tax/100*20, 2, '.', '');
return $this->addedTax;
}
/**
*Get the price
**/
public function get_price()
{
$this->addedTax = number_format($this->tax/100*20, 2, '.', '');
$this->price = number_format($this->tax-$this->addedTax,2,'.','');
return $this->price;
}
}
?>

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.