Function - PHP Include and Class Scope

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I am having a problem with var scope in a script iam developing, right now i think i will have to rewrite all my methods but lets see if someone can point me to the right direction.

file1.php

<?php
$db = new SystemDB();
include( file2.php );
someFile2Function();
?>

file2.php

<?php
function someFile2Function(){
    $db = new Database;
    include( class.php );
    $class = new CustomClass();
    $class->someMethod();
}
?>

class.php

<?php
class CustomClass {

    function someMethod(){
        global $db; <-- this var is the file1.php var and not the file2.php function var
        // execute some query
    }

}
?>

My problem is that inside the class the var $db that is using is the one in file1.php and not the one in someFile2Function() in file2.php.

Is there a way to use global $db that uses the var $db declared on someFile2Function();

Thanks.

Answers

as @RiggsFolly mention it s not a good idea to gave global in class, since there are conflict possibilities. Use it as parameter, that change dynamically, depend on what method/object calling it.

 function someMethod($db){
     var_dump($db);
  }

And also rather move function in file2.php to function from the class, if this function only needed by this class

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/38732396/php-include-and-class-scope

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils