0

I am trying to get a class working but for some reason I cannot get find the variables I have built into the class. Here is the code for the class: class file url (cls_question_object.php)

class question_object{

// the id to the question
public $i_id = "";

// the question string
public $s_qString = "";

// the question type
public $s_qType = "";

/* the array of answer strings
*/
public $a_qAnswerStrings = array();
    public $a_qAnswerSet = array("id"=>"","string"=>"");

}

And here is the code that I am testing my class with: file url (test_question_object.php)

include("cls_question_object.php");

/* - test for class question object -
*/

$cls_obj = new question_object;
$cls_obj->$i_id = "1";
$cls_obj->$s_qString = "test question string";
$cls_obj->$s_qType = "fib";
$cls_obj->$$a_qAnswerStrings[0]['id'] = "0";
$cls_obj->$$a_qAnswerStrings[0]['string'] = "test answer string";

print_r($cls_obj);

Here is the error I am getting:

Notice: Undefined variable: i_id in C:\wamp\www\Exam Creator\test_question_object.php on line 9
1
  • Please don't prefix your variables with things like i_ for integers or s_ for strings. That is an incredibly out-dated practice, and has particularly little value in PHP where the type of a variable can and will change to suit its use. You're only going to produce ugly, difficult to maintain code this way. Commented Mar 21, 2011 at 2:22

2 Answers 2

2

You can access these instance variables by doing:

$cls_obj->i_id = "1";

rather than:

$cls_obj->$i_id = "1";

However it is generally not good practice to make instance variables public, rather make them private and make mutator methods.

You would do something like this:

private $i_id = "";

public function getId(){
  return $this->id;
}

public function setId($id){
  $this->id = $id;
}

and you would access these functions like this:

$cls_obj = new question_object();
$cls_obj->setId(5);
$id = $cls_obj->getId();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this. I will definitely put this into practice.
1

$obj->$field_name this wrong, please use $obj->field_name to access your object's field. in your case it's should be used like this:

$cls_obj = new question_object;
$cls_obj->i_id

1 Comment

This is the answer to the question. Doing it the other way means it will try to access the class variable that has the name of the value stored in $i_id - Kind of like how $$var works. There is no $i_id - hence your undefined notice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.