By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,967 Members | 1,684 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,967 IT Pros & Developers. It's quick & easy.

OOP: How to use a member outside a method

100+
P: 348
Hello all. I used to have hair, but now I don't. We can thank OOP for this. :)

I have an employee class and a second script where all of my calls are for the employee class.

I need to build some validation into this application. My problems are with dropdown boxes.

In my second script, I instantiate the object and all is well and good. I get a return value from the method and if true, write to the db, if false, I need to display an error. This is where all of my issues are at.

I thought about using a SESSION but couldn't get that to work. I tried a POST var and couldn't get that to work either. By the way, this form is posting back to itself. Not sure why POST wouldn't work.

Then it dawned on me that the simplest way I can think of to accomplish this task is by creating another method called ShowError()

[PHP]
public function ShowError($error)
{
$this->error = $error
return $this->error;
}
[/PHP]

In the constructor, I have initialized the var $error as a member and set the variable as public.

Outside of the ShowError() method, I am attempting to call the member but it will not echo. What gives? I know I am doing something wrong but I haven't got a clue.

Should I be using global for this? I thought with OOP I could call that member ANYWHERE in the class.

Could someone please help?

Thanks,

Frank
Aug 17 '08 #1
Share this Question
Share on Google+
11 Replies


dlite922
Expert 100+
P: 1,584
syntax error. Do you have error reporting on?

why don't you use echo statements everywhere to track the logic of the application.

You didn't give much code to go on except a function that updates a (hopefully private) data member.


You need to learn about MVC if you're having difficulty with OOP. I'm sure you're like oh great another three letter acronym to learn, but trust me it's not that hard.

MVC stands for Model View Controller, its not represented by code, but by code structure.

Model: your database class that interacts with your datasource (usually database)
Controller: Your application logic, validations, calculations, etc.
View: Your HTML and echo statements (no extensive program logic here)


For a particular page in application you'll most likely have at least 4 files.

let's say i want to have a page that manages employees, my files will be like so:

employee.php = this simply determines what to do. what the actions of the page is (ie was it "delete employee", "add employee", etc) from (usually) a POST variable. It then calls the necessary function of the controller to do just that. For example $empController->deleteEmployee($_POST['empID']).

empController.php = contains the class with the necessary functions that employee.php needs. It interacts with the model (usually called VO , Value Object) if it needs to access the database. For example it might call the empVO->delete($id) function to delete an employee.

empVO.php = this is the class responsible for interactions with the employee table. It must have access to a class that connects to the database and prepares the database before hand. (maybe calls it in its constructor).



For small applications, MVC is not necessary, but it sure saves hours of coding when you're doing medium to large applications.

There are many benefits of MVC, google to find out.

Take care,


Dan
Aug 17 '08 #2

Atli
Expert 5K+
P: 5,058
Hi.

The method you posted is somewhat redundant, isn't it?

You basically take string as a parameter, set a class member, and then return that same string. Why bother doing all that when you already have the error string outside the class?

Anyways...
I don't really get the problem.
You are using your employee class to validate some user info. Then, based on that validation, you either mess with your database, or display an error.

Where is the problem here?
This sounds like a simple if statement to me.

Are you trying to display this error on a different page?
What is wrong with simply echoing an error if the validation fails?

As to Dan's MVC suggestion, I would have to agree.
A MVC system can dramatically simplify the inner workings of a large application.
I wouldn't recommend it tho unless you have a good grasp on basic OOP concepts.
Aug 17 '08 #3

100+
P: 348
fjm
Hey Dlite, thanks for the explanation and the advice. I used a rad a while back that used MCV but I am not familier with the concept really. I will look into that for sure.

Is this a standalone framework or what? I did a quick search but didn't find anything other than phpmvc.net. Is this the same thing you are talking about?
Aug 18 '08 #4

100+
P: 348
fjm
Hi Atli,

Thank you for responding. Here is the CheckRt method in the employee class

[PHP]
public function CheckRt($c,$l,$o,$r,$i,$d)
{
$this->c = $c;
$this->l = $l;
$this->o = $o;
$this->r = $r;
$this->i = $i;
$this->d = $d;
if($r)
{
if($r == 'comp' )
{
if(!$i)
{
return false;
}
elseif(!$d)
{
return false;
}
}
return true;
}
else
{
return false;
}
}
[/PHP]
body.php calls this method then forwards that return value back into the employee class, into a different method where I have html.

This value will now echo "data inserted" or "data not inserted". I don't feel like this is the correct method of doing things.

What I wanted originally when I created this post was to show the user which dropdown box they forgot to choose. I can't seem to get that though.
Aug 18 '08 #5

dlite922
Expert 100+
P: 1,584
Hey Dlite, thanks for the explanation and the advice. I used a rad a while back that used MCV but I am not familier with the concept really. I will look into that for sure.

Is this a standalone framework or what? I did a quick search but didn't find anything other than phpmvc.net. Is this the same thing you are talking about?
No this is one you should build on. I mentioned that's how I built mine and use it.

If your interested in using mine, PM me and i'll give you the files. And walk you through it on IM or Skype or something.


Dan
Aug 18 '08 #6

dlite922
Expert 100+
P: 1,584
Hi Atli,

Thank you for responding. Here is the CheckRt method in the employee class

[PHP]
public function CheckRt($c,$l,$o,$r,$i,$d)
{
$this->c = $c;
$this->l = $l;
$this->o = $o;
$this->r = $r;
$this->i = $i;
$this->d = $d;
if($r)
{
if($r == 'comp' )
{
if(!$i)
{
return false;
}
elseif(!$d)
{
return false;
}
}
return true;
}
else
{
return false;
}
}
[/PHP]
body.php calls this method then forwards that return value back into the employee class, into a different method where I have html.

This value will now echo "data inserted" or "data not inserted". I don't feel like this is the correct method of doing things.

What I wanted originally when I created this post was to show the user which dropdown box they forgot to choose. I can't seem to get that though.
I don't understand why you're choosing one letter names for your variables.

If I was the programmer that was hired after you, I'd be mad at you for coding things like that. Make your code a little understandable.


Do do what you asking is validation of checkmarks.

let's say you have
Expand|Select|Wrap|Line Numbers
  1. <input type="checkbox" name="test" value="test" />
  2.  
Your controller class could have the values as a data member. Following the framework I previously mentioned. Your .php file will call the function of the CT that reads your page (POST) variables.

[PHP]

$empCT = new EmployeeCT();

$empCT->readPost();

/* this will set the variables in something like this:

echo $empCT->data['test']

but of course there's no need to out put this in your php file. You validation function would use it.

so you would call:
*/

if($empCT->validatePageVals()}
{
// perform action if values validate
}


// your validatePageVals() function might look like this:

public function validatePageVals()
{
if($this->data['test'] == "")
{
echo "Please check mark test before continuing";
// or you could add to an error array.
array_push($this->errors,"Test checkmark not checked, cannot continue");
}


}

[/PHP]



I hope that makes sense to you. post all your code and tell us what *exactly* is not working and i'll try to help one more time.




Dan
Aug 18 '08 #7

Atli
Expert 5K+
P: 5,058
Dan.

In a MVC structure, shouldn't the View be responsible for the output?
Doesn't the echo statement in the Control kind of mess up that concept?
Not to mention all the stuff going on outside the MVC structure.

I've always operated under the impression that the Control should handle the business logic, that is; which Models and Views should be called, and how they should be used, but that the Control should never be used to directly handle or output data.

In short, the Control would only be used to create, operate and pass data between the Models and Views, based on the user input (typically using navigation parameters passed via the GET protocol).
The Models would be responsible for handling the data, and the Views for displaying it.

Which would leave the global scope clear of everything, except including resources, creating and initializing the Control object.

Or am I completely missing the point?

What I wanted originally when I created this post was to show the user which dropdown box they forgot to choose. I can't seem to get that though.
Ok, that we can do. Although, the rest of your post didn't really make much sense :P

Considering the direction this discussion has turned into, and the fact that this is extremely hard to explain in words, I'm going to post a "little" example of how I would go about doing this using a MVC approach.
(Or at least what I've always considered to be MVC, correct me if I'm wrong, please)

The Control
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. /**
  3.  * The Control. Responsible for operating the Model and View objects.
  4.  **/
  5. class Control 
  6. {
  7.     private $_model;
  8.     private $_view;
  9.  
  10.     /**
  11.      * Initialize the Model and View needed.
  12.      **/
  13.     public function __construct()
  14.     {
  15.         $this->_model = new Model();
  16.         $this->_view = new View();
  17.     }
  18.  
  19.     /**
  20.      * Entry point for the MVC application.
  21.      **/
  22.     public function Execute()
  23.     {
  24.         // Validate the boxes
  25.         $boxValidation = $this->_model->ValidateBoxes();
  26.  
  27.         // Print content based on the validation
  28.         if($boxValidation == false || is_array($boxValidation)) {
  29.             // Boxes are invalid. Print the form
  30.             $this->_view->PrintForm($boxValidation);
  31.         }
  32.         else {
  33.             // Use the data.
  34.             $success = $this->_model->UseBoxData();
  35.  
  36.             // Print a success message
  37.             $this->_view->PrintSucessMessage($success);
  38.         }
  39.     }
  40. }
  41. ?>
  42.  
The Model
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. /**
  3.  * The Model. Responsible for handling the data
  4.  **/
  5. class Model 
  6. {
  7.      /**
  8.         * Looks for each box in the POST array and creates an array containing
  9.      * the default value for each box. If a box is invalid, it's value is false.
  10.      *
  11.      * If none of the boxes are found, the function returns false.
  12.      * If all boxes are valid it returns true.
  13.      * Otherwise, it returns the default value array.
  14.         **/
  15.     public function ValidateBoxes($defaultValue="Select please") 
  16.       {
  17.         // Create an array of required boxes that should be checked.
  18.           $selected = array("first" => true, "second" => true, "third" => true);
  19.         $allValid = true;
  20.         $nothingPosted = true;
  21.  
  22.         // Go through each box. If it is not set, or it still contains
  23.         // the default value, set it as false.
  24.         // Otherwise, store the selected value.
  25.         foreach($selected as $_key => &$_value) 
  26.         {
  27.             if(isset($_POST[$_key])) {
  28.                 if(!empty($_POST[$_key]) && ($_POST[$_key] != $defaultValue)) {
  29.                     $_value = $_POST[$_key];
  30.                 }
  31.                 else {
  32.                     $_value = $allValid = false;
  33.                 }
  34.                 $nothingPosted = false;
  35.             }
  36.         }
  37.  
  38.         // Return FALSE if nothing was posted, TRUE if everything was valid
  39.         // Otherwise, return the requiredBoxes array.
  40.         return ($nothingPosted ? false : ($allValid ? true : $selected));
  41.     }
  42.  
  43.       /**
  44.        * Function that is called once the data has been submitted and validated
  45.        **/
  46.       public function UseBoxData()
  47.       {
  48.           // Do whatever it is you want to do with the POST'ed data
  49.         if(/* Your code succedded */ true) {
  50.             return true;
  51.         }
  52.         else {
  53.             return false;
  54.         }
  55.       }
  56. }
  57. ?>
  58.  
The View:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. /**
  3.  * The View. Responsible for creating the output.
  4.  **/
  5. class View
  6. {
  7.     private $_boxes = array();
  8.  
  9.     /**
  10.      * Initialize the <select> boxes and their options
  11.      **/
  12.     public function __construct()
  13.     {
  14.         // Set up the boxes and their options
  15.         $this->_boxes = array(
  16.             "first" => array(
  17.                 "default" => "Select please",
  18.                 "option1" => "The first option",
  19.                 "option2" => "The second option"
  20.             ),
  21.             "second" => array(
  22.                 "default" => "Select please",
  23.                 "option1" => "The first option",
  24.                 "option2" => "The second option"
  25.             ),
  26.             "third" => array(
  27.                 "default" => "Select please",
  28.                 "option1" => "The first option",
  29.                 "option2" => "The second option"
  30.             )
  31.         );
  32.     }
  33.  
  34.     /**
  35.      * Prints the <select> boxes.
  36.      * The $select parameter should contian the data returned by the
  37.      * Model's validation method.
  38.      * If the $selected parameter is FALSE, it is assumed that
  39.      * this is the first time the form is being shown, and it will not
  40.      * show any errors.
  41.      **/
  42.     public function PrintForm($selectedBoxes=false)
  43.     {
  44.         // Print the form header
  45.         echo "<form action='{$_SERVER['PHP_SELF']}' method='post'>\n";
  46.  
  47.         foreach($this->_boxes as $_boxname => $_boxoptions) {
  48.             // Check if the box is valid. Set the error message if it isn't
  49.             $error = "";
  50.             if(is_array($selectedBoxes) && $selectedBoxes[$_boxname] == false) {
  51.                 $error = "<span style='color: red'>You forgot this one!</span>";
  52.             }
  53.  
  54.             // Print the select box
  55.             echo "\t<select name='$_boxname'>\n";
  56.  
  57.             // Print the options
  58.             foreach($_boxoptions as $_optionname => $_optionvalue) {
  59.                 // Check if the current option was selected last time this was posted
  60.                 $selectedOption = "";
  61.                 if(is_array($selectedBoxes) && $_optionvalue == $selectedBoxes[$_boxname]) {
  62.                     $selectedOption = "selected";
  63.                 }
  64.  
  65.                 // Print the option
  66.                 echo "\t\t<option $selectedOption name='$_optionname'>$_optionvalue</option>\n";
  67.             }
  68.  
  69.             // Close the select and add the error (if any)
  70.             echo "\t</select> {$error}<br />\n";
  71.         }
  72.  
  73.         // Print submit button
  74.         echo "\t<input type='submit' />\n";
  75.  
  76.         // Close the form
  77.         echo "</form>\n";
  78.     }
  79.  
  80.     /**
  81.      * Prints a message based on the $success boolean.
  82.      **/
  83.     public function PrintSucessMessage($success)
  84.     {
  85.         if($success) {
  86.             echo "<h1>Your data has been received!</h1>";
  87.         }
  88.         else {
  89.             echo "<h1>There was an error processing your form!</h1>";
  90.         }
  91.     }
  92. }
  93. ?>
  94.  
And finally, how I would call this in my index file:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $control = new Control();
  3. $control->Execute();
  4. ?>
  5.  
Aug 18 '08 #8

100+
P: 348
fjm
What kind of freakish programming is this? :P

Do people really program like this in the "real world"? It would have taken me a day to program 3 little selects with validation. :)

Actually, it is really cool. I gotta study that cuz it blows my mind to see all that code for just 3 boxes.

Atli, did you program that by hand or pull it from a RAD? It is truly an amazing piece of code.

I'm frickin speechless.. :) Let me go study it a bit cuz now I am really intregued!

@Dan - I was being lazy is all. That's why I used single letters. :P

Frank
Aug 18 '08 #9

dlite922
Expert 100+
P: 1,584
Dan.

In a MVC structure, shouldn't the View be responsible for the output?
Doesn't the echo statement in the Control kind of mess up that concept?
Not to mention all the stuff going on outside the MVC structure.
see my comment. echo was by accident, I was just really trying to show him that he could store the page variable in the CT's "data" member.

is all.

Haven't read your code yet though, too late going to bed ;)


Dan
Aug 18 '08 #10

dlite922
Expert 100+
P: 1,584
What kind of freakish programming is this? :P

Do people really program like this in the "real world"? It would have taken me a day to program 3 little selects with validation. :)

Actually, it is really cool. I gotta study that cuz it blows my mind to see all that code for just 3 boxes.

Atli, did you program that by hand or pull it from a RAD? It is truly an amazing piece of code.

I'm frickin speechless.. :) Let me go study it a bit cuz now I am really intregued!

@Dan - I was being lazy is all. That's why I used single letters. :P

Frank
This programming is not for a single page. it's for an application. If you are doing one page with 3 drop downs you wouldn't need this, but I bet you the project your working on is or will be bigger than this single page.


Cheers,



Dan
Aug 18 '08 #11

100+
P: 348
fjm
Hey Dan,

I have created several large scale projects and have never used MVC. It seems like overkill. I used to say that about OOP but MVC in my opinion is way too much. Interesting concept tho.
Aug 18 '08 #12

Post your reply

Sign in to post your reply or Sign up for a free account.