开发者

PHP, Unidentified variable in a class

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"=&g开发者_JAVA技巧t;"");

}

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


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();


$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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜