Classes and scope of php variables

Asked

Viewed 174 times

1

You see, my question is more about how to reference and "get" the content of a variable in a PHP Class. See excerpts of the code below, where I put wrong data for the connection, on purpose, to cause an exception of PDO, and so store the error msg in the msgErro variable. So far, so good, only that debugging the code (with Xdebug), I see that in the file that has the class and the msgErro variable, it is created in a good way, I visualize its content (which is the connection error), however, when the debugging advances, and goes back to the PHP of the register, I look at the debugger, this shows the local variables, in the case the object that took the class properties, but the property value (variable) $u->msgErro is empty (empty)! and that’s what I can’t figure out how it gets empty, if a line earlier in the variables in the.php file, where the class is, was with content.

php. . .

    $u->conectar("xxxx","xxxx","xxx","");
    if ($u->msgErro == "") 

user file.php // containing the class

Class Usuario 
{
    private $pdo;
    public $msgErro; //tudo ok

    public function conectar($nome, $host, $usuario, $senha){
            global $pdo;
            try 
            {
                $pdo = new PDO("mysql:dbname=".$nome.";host=".$host,$usuario,$senha);
            }
            catch (PDOException $e)
            {
                $msgErro = $e->getmessage();
            }
    }
}

When I test the $msgErro variable in the file register, through the object $u = new User;

        if ($u->msgErro == "") 
    {
        echo "esta mensagem ´é se msgErro está vazia!";

That is, in this test, there should be a negative of if, because there was error in the connection, the error was placed in the variable $msgErro there in the file users.php, however, in the test of the file register.php, the variable is empty, so it goes straight through if. Any tips? Grateful.

  • 1

    The best tip is to stay smart, if you really dedicate yourself to learning how to program, you will notice that almost every "teacher" of PHP does not understand any programming crap, and that almost always, using OO in PHP can be considered ignorance. I know if you ask around they’ll say it’s absurd, but it’s that thing, it depends on how much you really want to be a programmer. If you have time, learn how to program with C, C++, C#, and even Java. Then it will be easier to really learn, because in these more serious languages people can’t pretend to be programming.

1 answer

2


If you want to refer to the class member, and not to any variable, you need to make explicit:

catch (PDOException $e)
{
    $this->msgErro = $e->getmessage();
}
//    ^
//    |
//     --------- O $this se refere à instância atual do objeto.
//               se fosse membro estático seria self::membro
//               (o self faz bypass na vtable do objeto,
//               definitivamente acessando a implementação original)

See error :) in IDEONE, as expected.


Not that it has anything to do with the original problem, but look at the scope "salad" you’re making with $pdo:

private $pdo;
public $msgErro; //tudo ok

public function conectar($nome, $host, $usuario, $senha){
   global $pdo;
   try 
   {
      $pdo 
   ...

Is not using $this, has a global left, and still a private.

If you want to do the OO "right", and need to reuse the PDO (it does not seem to be your case), insert the PDO in the constructor or method, if it is not this way make a subclass (I do not like, but it is better than global), but do not depend on global. Loses all meaning.

  • Bacco, great tip (it worked here, putting the pseudo-variable $this). Now, kindly explain: could you also use, in this case, the other pseudo-variable self:: ? and how would that be? because I tried self:: msgerro = $e->getmessage(); but gave error: ( ! ) Parse error: syntax error, Unexpected '=' in C: xampp htdocs LOGIN SCREEN CLASSES usuarios.php on line 16. PS: very grateful indeed!

  • The self:: normally you will use when you only have static members, it is good to read the classes part of the php manual itself. https://secure.php.net/manual/en/index.php

Browser other questions tagged

You are not signed in. Login or sign up in order to post.