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!
<?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 ?
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.
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";
}
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 ?
$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
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");