PHP Class and Methods -


i new world of coding php , ventured territory of objects, classes , methods. having hard time understanding how use object oriented coding in following code attempting put together. have form users required fill in first name, last name , email address. first step validating if user has filled in of data

hence code looks such

class myform {  var $firstname, $lastname, $email;  function user($firstname, $lastname, $email) { $fname = isset($_post['fname']) ? $_post['fname'] : ''; $lname = isset($_post['lname']) ? $_post['lname'] : ''; $email = isset($_post['email']) ? $_post['email'] : '';  errormsg = array():  if(empty($fname)) {             $errormsg[0] = 'please enter first name';         }          if(empty($lname)) {             $errormsg[1] = 'please enter last name';         }          if(empty($email)) {             $errormsg[2] = 'please enter email address';         } } } } 

now within html page instantiating object

<?php $validate = myform(); $validate->user($firstname, $lastname, $email) ?> 

when submit form, error variables $firstname, $lastname, $email have not been defined unless change function read below understand referencing variables opposed copying.

function user(&$firstname, &$lastname, &$email) 

now second question have have read shouldn't assign values data members or variables follows

<?php     $validate = myform();     $validate->firstname = isset($_post['fname']) ? $_post['fname'] : '';     $validate->user($firstname, $lastname, $email)     ?> 

since these class variables shouldn't need set them way are... user operates regular function in code posted html code you're saying "in instance of form named 'validate' run function user values null, null , null'. class declares 3 values, can cut them out of declaration.

that being said classes still utilize private , protected variables, inside of user function if put $username = 'foo'; it's not going change value of variables class itself. need $this->firstname = $_post['fname'];

you're fundamentally flawed in way you're thinking class, , should build function sets firstname, lastname , email , call function inside class...

class myform {  public $firstname, $lastname, $email;  function setusername($value) {     //add form input sterilization here     $this->firstname = $value;     }  } 

then in main code call

$validate = new myform; $validate->setusername($_post['fname']); 

Comments