简体   繁体   中英

Unknown property with class variable PHP in Yii encountered in unit testing

In a data access object using SQL for prepared statements, I have several strings with the SQL and binding variables initialized. One such is

private $insertQuestionSql = "
INSERT IGNORE INTO bgt.question_models (nodeId, questionId, parentId, state, version,
questionText, userResponseText) 
VALUES (NID, QID, PID, ST, V, QT, URT)";

This statement is declared and used in the same class as the DAO function

public function createQuestion(QuestionTemplateModel $qt) {
  //create database connection and initialize transaction
  $connection = Yii::app()->db;
  $transaction = $connection->beginTransaction();

  try {
    $command = $connection->createCommand($this->insertQuestionSql);

In Yii, $connection is an instance of CDbConnection and returns an instance of CDbCommand via the createCommand function.

Since I'm accessing this property within the class, I should be able to access the string variable. Why is that not happening here?

The full error is

"Unknown property 'insertQuestionSql' for class 'QuestionDAOTest'."

This behavior happens regardless of

  • Changing SQL string
  • Removing first newline character

In addition, removing the $this-> results in an undefined variable: insertQuestionSql error. This occurs despite changing the access modifier to both public and protected

I don't know if this will be helpful to anyone, but I figured out a solution.

First, the CDbCommand::bindParam follows the standard PHP PDOStatement::bindParam() syntax in which the placeholders on which variables are to be bound must have the prefix : . Without that prefix, the variables were not being bound to the SQL statement.

Second, for some reason, private $insertQuestionSql was always found to be an unknown property when accessing within the class, despite usage of $this-> prefix when calling the variable. I worked around this by converting the property to static and calling via

$command = $connection->createConnection(QuestionDAO::$insertQuestionSql);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM