Unknown Property Exception Thrown In Unit Testing

I’m writing a DAO layer for a webapp I’m developing. In addition, I’m a big believer in unit testing. Finally, since the database is pretty complicated as far as relations are concerned, I’ve run into major issues using ActiveRecord and have fallen back to using straight SQL and PDO objects.

Given a QuestionTemplateModel with several fields, including an array of ResponseLabelModel objects, I want to test the basic CRUD operations of the data model.

To do this, I have a QuestionDAO object defined, and one of the functions is




  public function createQuestion(QuestionTemplateModel $qt) {

    //create database connection and initialize transaction

    $connection = Yii::app()->db;

    $transaction = $connection->beginTransaction(); 

    

    try {

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


      $this->insertQuestion($qt, $command);

      $this->insertLabels($qt->getResponseLabels, $command);

      $this->insertMappings($qt->getNodeId, $qt->getParentId, $command);

      

      $transaction->commit();

      return "successful";


    } catch (Exception $e) {

      $transaction->rollback();

      return $e;

    }

  }



Here, the $this->insertQuestionSql property used in the createCommand call is defined in the same class via




private $insertQuestionSql = "INSERT IGNORE INTO bgt.question_models (nodeId, questionId, parentId, state, 

version, questionText, userResponseText) VALUES (NID, QID, PID, ST, V, QT, URT)";

  



My issue is that within the QuestionDAOTest object, I get differing errors based on what the access modifier is.

If the modifier is private or public with $this->insertQuestionSql, I get the exception Exception: Unknown property ‘insertQuestionSql’ for class ‘QuestionDAOTest’.

If I remove the $this-> and stick with plain $insertQuestionSql, I get the exception Undefined Variable.

Note that this ocurs whether or not line breaks exist in the SQL statement.

Any help is really appreciated!

It turned out that this was a two-fold problem.

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 latter part is a hack, since why should an internal variable need to be declared static for internal usage?