PHPSA\Compiler\Expression::declareVariable PHP Method

declareVariable() public method

public declareVariable ( PhpParser\Node\Expr\Variable $expr, mixed $value = null, integer $type = CompiledExpression::UNKNOWN ) : CompiledExpression
$expr PhpParser\Node\Expr\Variable
$value mixed
$type integer
return PHPSA\CompiledExpression
    public function declareVariable(Node\Expr\Variable $expr, $value = null, $type = CompiledExpression::UNKNOWN)
    {
        $variable = $this->context->getSymbol($expr->name);
        if (!$variable) {
            $variable = new Variable($expr->name, $value, $type, $this->context->getCurrentBranch());
            $this->context->addVariable($variable);
        }
        return new CompiledExpression($variable->getType(), $variable->getValue(), $variable);
    }

Usage Example

Example #1
0
 /**
  * @param \PhpParser\Node\Stmt\Foreach_ $stmt
  * @param Context $context
  * @return CompiledExpression
  */
 public function compile($stmt, Context $context)
 {
     $expression = new Expression($context);
     $expression->compile($stmt->expr);
     if ($stmt->keyVar) {
         $keyExpression = new Expression($context);
         $keyExpression->declareVariable($stmt->keyVar);
     }
     if ($stmt->valueVar) {
         $valueExpression = new Expression($context);
         $valueExpression->declareVariable($stmt->valueVar);
     }
     if (count($stmt->stmts) > 0) {
         foreach ($stmt->stmts as $statement) {
             \PHPSA\nodeVisitorFactory($statement, $context);
         }
     } else {
         return $context->notice('not-implemented-body', 'Missing body', $stmt);
     }
 }