Camadas
Camadas

Reputation: 509

Access a constructor into a function on PHP

I want to try to access my constructor $mysql that I have declared ouside the class ( When I put inside the class it wont work ) and I wanted to have access to it inside the methods that I create throught the all class.

Here is the code:

<?php
require_once ("db.php");
$mysql = new DbConnector();
class Validar
{
    private $nifProgram;
    private $checkProgram;
    private $result;

    public function getInfo($nifProgram, $checkProgram)
    {
        $this->nifProgram = $nifProgram;
        $this->checkProgram = $checkProgram;
        echo $this->nifProgram . " - " . $this->checkProgram;
        $this->validate();
        return $this->result;
    }

    private function validate()
    {
    }
}?>

If I put inside the class ( like the other variables are ) I get this error: syntax error, unexpected '$mysql', expecting 'function'

Thanks in advance

Upvotes: 0

Views: 54

Answers (2)

brianmearns
brianmearns

Reputation: 9967

Just pass it as a function argument, for instance, to the constructor:

<?php
require_once ("db.php");
$mysql = new DbConnector();
$validar = new Validar($mysql);
class Validar
{
    private $nifProgram;
    private $checkProgram;
    private $result;
    private $dbconn;

    public function __construct($dbconn)
    {
        $this->dbconn = $dbconn;
    }

    public function frobnicate()
    {
        //Now you can access the db connector as:
        $this->dbconn;
    }

    public function getInfo($nifProgram, $checkProgram)
    {
        $this->nifProgram = $nifProgram;
        $this->checkProgram = $checkProgram;
        echo $this->nifProgram . " - " . $this->checkProgram;
        $this->validate();
        return $this->result;
    }

    private function validate()
    {
    }
}?>

As far as the error you get when you try to put it inside the class, e.g.:

class Validar 
{
    $mysql = new DbConnector();
}

What this looks like to the php parser is that you're declaring an member variable (a "property") of the class, named mysql, and you're trying to initialize it using the statement new DbConnector(). Unfortunately, PHP only allows you to initialize properties using constant expressions, such as string or numeric literals, null, etc. From the PHP manual:

This declaration may include an initialization, but this initialization must be a constant value

So you could also just instantiate the DbConnector directly in the constructor function, if you don't need to be able to pass it in. Either way would work fine, it all just depends on your requirements.

Upvotes: 4

Daniel W.
Daniel W.

Reputation: 32290

The error is appearing somewhere inside of the brackets of a

class XXXXXX 
{
    //error is on this level
    //maybe you put here:
    $mysql = new Validar(); // or some other logic stuff
    //where it expects either variable declaration only
    //or a method
}

Upvotes: 0

Related Questions