Page 1 of 1

setting a class variable from a function

Posted: Wed Feb 22, 2006 7:02 am
by ed209
I want to be able to set a class variable depending on parameters defined when making the instance of a class, but it doesn't seem to work:

Code: Select all

<?php
class aClass{

var $sql_type = "";
var $sql_query = "";
var $db_data = ($this->sql_type == "SELECT") ? $this->get_data($this->sql_query) : '';

function get_data($sql_query){
   return "Some data from the database";
}

}
?>
I get "Parse error: parse error, unexpected '(' in..." for the var $db_data line. Am I not allowed to use an if statement when setting the variable ?


Thanks,
Ed.

Posted: Wed Feb 22, 2006 7:06 am
by jamiel
Why not do that logic in your constructor?

Posted: Wed Feb 22, 2006 7:15 am
by ed209
not really sure what you mean by constructor, is that what I call an instance of the class i.e.

Code: Select all

<?php

$my_class = new aClass;

$my_class->sql_type = "SELECT";
$my_class->db_data = ($my_class->sql_type == "SELECT") ? $my_class->get_data($my_class->sql_query) : '';
?>
I kind of wanted to aviod doing that as I like to put as much as I can in the class, and have less code on the rest of the pages.

Thanks for the reply,
Ed.

Posted: Wed Feb 22, 2006 7:23 am
by jamiel
A constructor is the function which is called automatically as soon as your class is instantiated. In PHP4 you should give the function the same name as your class.

Code: Select all

class aClass{ 
 
var $sql_type = ""; 
var $sql_query = ""; 
var $db_data; 
 
function aClass {
     $this->db_data = ($this->sql_type == "SELECT") ? $this->get_data($this->sql_query) : '';
}

function get_data($sql_query){ 
   return "Some data from the database"; 
}

Posted: Wed Feb 22, 2006 7:40 am
by ed209
that's handy, I didn't know that. I think there is a new problem though, I assume the contructor is called as soon as I create a new instance i.e. $my_class = new aClass; but I don't actually set the value of $my_class->sql_type until my class has been initiated (and the constructor called). Is this correct ?

therefore:

Code: Select all

$my_class = new aClass;  // constructor called which calls the get_data() function

$my_class->sql_type = "SELECT"; // get_data() function requires this variable to be set before it runs

Posted: Wed Feb 22, 2006 7:55 am
by jamiel
Pass a parameter to your constructor with the value of sql_type ...

Code: Select all

class aClass{  
  
var $sql_type;  
var $sql_query;  
var $db_data;  
  
function aClass($sql_type) { 
      
     $this->sql_type = $sql_type;
     $this->db_data = ($this->sql_type == "SELECT") ? $this->get_data($this->sql_query) : ''; 
} 
 
function get_data($sql_query){  
   return "Some data from the database";  
} 

}

$my_class = new aClass("SELECT");

Posted: Wed Feb 22, 2006 10:52 am
by ed209
thanks for your help. I don't think I can do it that way, but I've learnt something useful. I'm going to pass the data in separately.