[SOLVED] Can't call methods from a constructor

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Hendeca
Forum Commoner
Posts: 29
Joined: Tue Nov 18, 2008 1:27 pm

[SOLVED] Can't call methods from a constructor

Post by Hendeca »

Hello! I have a class that contains one method that returns a value based on the parameters submitted to the function. I want to create a constructor that takes the necessary values needed for the function, and then runs the function. So I tried creating a constructor that takes the parameters necessary for the function, and then runs the function from the constructor so that I only need to instantiate the class with the proper variables passed, and it will return the proper values. For some reason, I can't seem to successfully run the function from the constructor! I've tried running the function using just functionName(); and I've also tried using $this->functionName(); and self::functionName(); but no matter what I do, it doesn't seem to call the function. When I create a new instance of a class in a variable and then call the function from that variable, everything works. Here's an example of the code:

Code: Select all

<?php
	class ParamsChecker {

                function __construct($post, $get) {
                       CheckParams($post, $get);
                }
		
		public function CheckParams($post, $get) {
			
			$containsData = 0;
			$getParamsValid = 0;
			$validParams = array('artist','album','genre','soundslike','mood');
			
			if(isset($post['searchsubmit'])) { //Check if the submit button has been pressed
				foreach($post as $key=>$value) { //If so, loop through the post array
					if($key != 'searchsubmit') { //Ignore the submit button value, since we already know the submit button's been pressed
						if($value = '') { //Check to see if the search text boxes contain any value
							$containsData += 0; //If the search box is empty, add nothing to the $containsData variable, keeping its value false
						} else {
							$containsData++; //If the search box contains data, add 1 to $containsData, making it true
						}
					}
				}
				if($containsData) { //If any of the search boxes contain data, change $status so the code knows to show search results
					$status = 'ShowSearchResults';
				} else { //Otherwise, change $status so code knows to display an error message
					$status = 'ShowErrorMessage';
				}
			} else if(isset($get['param'])) { //If the submit button hasn't been pressed, check to see if a $_GET variable exists
				foreach($validParams as $value) { //Loop through the $_GET variable
					if($get['param'] != $value) {
						$getParamsValid += 0; //If the $_GET parameter doesn't contain a valid parameter name, keep $getParamsValid false
					}
					else {
						$getParamsValid++; //Otherwise, make the $getParamsValid variable true
					}
				}
				if($getParamsValid) {
					$status = "ShowCategory";
				} else {
					$status = "DoNothing";
				}
			} else {
				$status = "DoNothing"; //If the $_POST and $_GET variables are both empty, tell the script to do nothing
			}
			
			return $status;
		}
	}
?>
I want to call the function immediately after the instantiation of the class, but that doesn't seem to work. See the following code:

Code: Select all

$status = new ParamsChecker($_POST, $_GET);
var_dump($status);
The variable dump show that $status is a ParamsChecker object, but the value returned by the CheckParams() function isn't returned. If I remove the constructor and call the method the following way everything works:

Code: Select all

$checker = new ParamsChecker();
$status = $checker->CheckParams($_POST, $_GET);
I'm not sure what I'm doing wrong, but I'd like to be able to call another method from the class in the constructor. Maybe it's a scope problem? I'm not sure... Thanks in advance for any help!
Last edited by Hendeca on Sat Apr 17, 2010 7:14 pm, edited 1 time in total.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Can't call methods from a constructor

Post by requinix »

Unlike other languages, if you want to get something inside a class (from within that class) you need $this for regular stuff and self:: for static stuff. So

Code: Select all

function  __construct($post, $get) {
       $this->CheckParams($post, $get);
}
Hendeca wrote:The variable dump show that $status is a ParamsChecker object, but the value returned by the CheckParams() function isn't returned.
Unless you put the returned $status somewhere, in the class, you won't see it.

Also,

Code: Select all

if($value  = '') {
Missing something there.
Hendeca
Forum Commoner
Posts: 29
Joined: Tue Nov 18, 2008 1:27 pm

Re: Can't call methods from a constructor

Post by Hendeca »

Thanks so much for your response!

Well, I've tried using $this->CheckParams($post, $get) but still I'm not getting a return value. The value of $status (in the class) is returned at the end of the method I'm calling and when I call the method this way:

Code: Select all

$checker = new ParamsChecker();
$status = $checker->$CheckParams($_POST, $_GET);
I can do a variable dump on $status and get the proper return value. Maybe there's an error elsewhere in my code? I'm thinking it may have something to do with my variables. I don't declare any public variables at the beginning of the class, only within the constructor function and within the CheckParams() function. Maybe I need to declare the $post and $get variables at the beginning of the class and put the values of the $_POST and $_GET variables passed at the instantiation of the class into the public variables at the beginning of the class. I'll try it out and post the results! Thanks again!
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Can't call methods from a constructor

Post by requinix »

There is no "$status in the class".

Like I said, if you want to access some part of a class you need $this-> or self::. Without you're only dealing with temporary, per-function variables. Once the function ends the variable goes away without a trace.
Hendeca
Forum Commoner
Posts: 29
Joined: Tue Nov 18, 2008 1:27 pm

Re: Can't call methods from a constructor

Post by Hendeca »

I see. Well I know that I am able to successfully return a value called $status but it is a variable defined within a method, not in the class. At the end of the CheckParams() method in my class, I return the value of $status (a variable defined in the function) and this is successful when I just call the method directly like so:

Code: Select all

$checker = new ParamsChecker();
$status = $checker->CheckParams($_POST, $_GET);
When I do a variable dump on $status, the correct value is returned. So that part of the script now works. The value of $status is then passed to a method in another class. The method in the second class first runs a function that uses a switch value to run a function based on the contents of the $status variable passed to it. At the end of each function called by the switch, the value of the variable $st is defined and returned. The strange this is that the switch statement successfully runs the correct function based on the value of $status, but fails to return the correct value of $st. Here's the code I'm referring to.

Code: Select all

<?php 
	class CatalogResultBuilder {
		
		function FunctionSwitch($post, $get, $link, $status) {
			switch ($status) { //Check to see what the contents of $status is, and depending on its value, perform the appropriate function
				case "ShowSearchResults":
					$this->ShowSearchResults($post, $link);
					break;
				case "ShowCategory":
					$this->ShowCategory($get, $link);
					break;
				case "ShowErrorMessage":
					$this->ShowErrorMessage();
					break;
				case "DoNothing":
					$this->DoNothing();
					break;
			}
		}
		
		function ShowSearchResults($post, $link) {
			$searchParams = 'SELECT * FROM catalog WHERE'; //Create a variable with the 
			$counter = 0; //This variable will determine the styling of a row based on whether it is odd or even
			foreach($post as $key => $value) { 
				$valueLength = strlen($value);
				if(($valueLength != 0) && ($key != 'searchsubmit')) { //Iterate through the $_POST array and determine if it contains data - also exclude the submit button's value
					$partialMatch = "'%".$value."%'"; //If it contains data, add % characters to match anything before or after the search field value
					$searchParams .= " ".$key." LIKE ".$partialMatch." &&"; //Add search field values to SQL query
				}
			}
			$query = substr($searchParams, 0, -2); //Strip extra ampersands off of the end of the query
			$query .= ';'; //Add a semi-colon to the end of the query
			$st = mysql_query($query, $link) or die(mysql_error()); //Query the database
			
			if(!$st) {
				$st = "Your search returned 0 results.";
			}
			
			return $st;
			
		}
		
		function ShowCategory($get, $link) {
			if (!is_null($get['param'])) { 
				$query = "SELECT * FROM catalog WHERE ".$get['param']."='".$get[$get['param']]."';"; //If the parameter value is not null, create a database query with the values
				$st = mysql_query($query, $link) or die(mysql_error()); //Query the database and store in $st
			}
			
			return $st;
		}
		
		function ShowErrorMessage() {
			$st = "Please enter a search word!";
			
			return $st;
		}
		
		function DoNothing() {
			
			echo "!!!!!!!!!";
			$st = "Enter a search!";
			
			return $st;
		}
	}
?>


And here's how I'm calling it:

Code: Select all

$builder = new CatalogResultBuilder();
$st = $builder->FunctionSwitch($_POST, $_GET, $link, $status);
The part I'm focusing on is the switch statement at the beginning:

Code: Select all

function FunctionSwitch($post, $get, $link, $status) {
			switch ($status) { //Check to see what the contents of $status is, and depending on its value, perform the appropriate function
				case "ShowSearchResults":
					$this->ShowSearchResults($post, $link);
					break;
				case "ShowCategory":
					$this->ShowCategory($get, $link);
					break;
				case "ShowErrorMessage":
					$this->ShowErrorMessage();
					break;
				case "DoNothing":
					$this->DoNothing();
					break;
			}
		}
And the function called DoNothing() :

Code: Select all

	function DoNothing() {
			
			echo "!!!!!!!!!";
			$st = "Enter a search!";
			
			return $st;
		}
I know the switch works, because I have checked the value of $status before passing it to FunctionSwitch() and it's value is "DoNothing". Based on the switch statement, if the value of $status is "DoNothing" it should run the DoNothing() function. The series of exclamation marks shows up successfully, showing that the switch statement is running the correct function. The problem now is that the value returned by the function DoNothing() is not "Enter a search!" as it should be, it comes out as NULL instead. Any idea why this is happening? Maybe it has to do with the fact that I'm using the same variable name ($st) in each function I run. Thanks again! I will keep trying to fix it and post any success I have.
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Can't call methods from a constructor

Post by AbraCadaver »

You're not going to return something from the constructor because the new statement is returning an object. You might do this:

Code: Select all

function  __construct($post, $get) {
       $this->status = $this->CheckParams($post, $get);
}
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
dejvos
Forum Contributor
Posts: 122
Joined: Tue Mar 10, 2009 8:40 am

Re: Can't call methods from a constructor

Post by dejvos »

Or just make the method CheckParams static

Code: Select all

<?php
class ParamsChecker {
    public static function CheckParams($post,$get){
         //put your code here
    }
}

// then call the method this vay
$result = ParamsChecker::CheckParams($post,$get);
var_dump($result);
?>
Hendeca
Forum Commoner
Posts: 29
Joined: Tue Nov 18, 2008 1:27 pm

Re: Can't call methods from a constructor

Post by Hendeca »

Thanks so much for your help, guys!

I got the script working with AbraCadaver's solution. Here's my newly updated code:

Code: Select all

function FunctionSwitch($post, $get, $link, $status) {
			switch ($status) { //Check to see what the contents of $status is, and depending on its value, perform the appropriate function
				case "ShowSearchResults":
					$st = $this->ShowSearchResults($post, $link);
					return $st;
					break;
				case "ShowCategory":
					$st = $this->ShowCategory($get, $link);
					return $st;
					break;
				case "Browse":
					$st = $this->BrowseCatalog($link);
					return $st;
					break;
				case "ShowErrorMessage":
					$st = $this->ShowErrorMessage();
					return $st;
					break;
				case "DoNothing":
					$st = $this->DoNothing();
					return $st;
					break;
			}
		}
I suppose the method calling the function is the method the variable is returned to. By storing the returned value and returning the variable in which it's stored instead of just calling the method, everything worked out. Each of the methods in the CatalogResultBuilder class returns the value of $st that it has stored, but it's specifically the FunctionSwitch method that's calling the other methods in the first place. Now, the value is returned to the FunctionSwitch method and returned again from the FunctionSwitch method to the php code that instantiates the class. Sorry if that's a terrible explanation ha! Everything works now. Thanks so much I really can't thank you enough!
Post Reply