Reputation: 475
student table contains: id firstname lastname
function get_db_fields get student table fields.
class Student{
public function get_db_fields(){
$sql = "SELECT * FROM students";
$result = mysql_query($sql);
if(!$result){
die("Failed :" . mysql_error());
}
$db_fields = array();
while($field = mysql_fetch_field($result)){
$db_fields[] = "'".$field->name."'";
}
return join(',',$db_fields);
}
public $db_fields = array($this->get_db_fields()); <--- This is not working
}
return join(',',$db_fields) = 'id','firstname','lastname'
my question is how I am going set the return value into public $db_fields. So public $db_fields will be "public $db_fields = array('id','firstname','lastname')"
What i've tried so far
1.)
public $db_fields = array($this->get_db_fields()); <--- This is not working
Error: Parse error: syntax error, unexpected T_VARIABLE in C:\Program Files\xampp\htdocs\ieti\includes\student.php on line 33
2.) $database_fields = $this->get_db_fields();
Error: Parse error: syntax error, unexpected T_VARIABLE in C:\Program Files\xampp\htdocs\ieti\includes\student.php on line 33
Upvotes: 0
Views: 257
Reputation: 2244
public $db_fields = array($this->get_db_fields());
One using the 'array' here is not right, it should just be
public $db_fields =$this->get_db_fields();
And two, classes have constructors for this...
so
public function __construct(){
$this->db_fields = $this->get_db_fields();
}
Moreover use of mysql_query is now discouraged, if you are using object oriented already use PDO.
Upvotes: 0
Reputation: 5683
Create a constructor and assign the returned value from get_db_fields
to the member variable db_fields
. Member variables can only be initialized with values that are evaluated at compilation.
class Student{
public $db_fields;
public function __construct() {
$this->db_fields = $this->get_db_fields();
}
// Rest of your code
Upvotes: 2