Search code examples
zephir

Using PDO in Zephir


As part of my experiments with Zephir I am currently trying to use PHP PDO to access a MySQL database. For starters I found that a relatively innocuous

$dbh = new PDO("mysql:host=localhost;dbname=dbn;","user","pwd");

when translated and used in Zephir

var dbh = new PDO("mysql:host=localhost;dbname=dbn;","user","pwd");

had Zephir throwing up an exception

var dbh = new PDO
------------^

which by dint of some searching I resolved - new is a reserved word in Zephir and must be replaced with $new.

var dbh = $new PDO("mysql:host=localhost;dbname=dbn;","user","pwd");

which promptly produced

var dbh = $new PDO(
-----------------^

which I resolved when I realized that I had to explicitly tell Zephir to use the PDO name space

use \PDO;
var dbh = $new \PDO::PDO(

Now, with

var dbh = $new \PDO::PDO("mysql:host=localhost;dbname=dbn","user","pwd");

I get

var dbh = $new \PDO::PDO(...,"user","pwd");
---------------------------------------------^

which makes little sense to me.

From what I can tell Zephir is still too young to be considered for a full port of a working PHP prototype. However, it looks like it is good enough to be used to port some of the more CPU intensive bits of a PHP application but its documentation is lacking. For instance, nowhere does it state in the docs that the right way to use an array is

array myArray;
 let myArray = [1,2,...];

Miss out the first list and the compiler complains about not being able to mutate.

With my current PDO problem there is a clearly something else that is wrong - how can I find what it might be?


Solution

  • The var keyword in zephir is for variable declarations. If you assign a "simple" value like a string or an array, it will work.

    The problem with your example is that new PDO(<arguments>) is an expression, where the var operator is not the right choice. So what you want is to assign a value.

    Variables are by default immutable. (see zephir-lang.com)
    That's why you need to use the let operator, which makes them immutable and is able to resolve expressions.

    So you need to use var and let
    like var dbh; let dbh = new \PDO(<arguments>);

    And if you do it that way, it works :)