Global variable in php

I have a userdb class in which I declare a function that returns a database connection:

 return $con = new PDO("mysql:host=$host;dbname=$db", $user, $pass); 

I have different functions, even in other classes where I need to access $con (for example, pass a request or get data), but I can not access this variable.

Is there a better way to define and use a database class? Remember that I have other classes where I need to access the userdb class.

+4
source share
7 answers

I would advise you to use Singleton Pattern for this:

In your userdb class, declare a static property of $scon :

 private static $scon; 

and provided that the function above is called createConnection() , you must create the following static method:

 public static function connect() { if (empty(self::$scon)) { $instance = new userdb(); self::$scon = $indtance->createConnection(); } return self::$scon; } 

With this, you can access your userdb connection with:

 userdb::connect(); 

Also, since this is a singleton, it will only connect once and use this connection until the end of the script.

Note (for dependency injection):. Since @ KevinM1 mentioned dependency injection, I must add that this is also a possible and far superior solution. This requires that you create the setConnection () (or abstract ancestor) method for all your classes using a database connection, and during the installation of these classes, you can use Factory to add the necessary connection to the object. This should be wrapped inside some class loader that represents your model structure.

You see, the world of the pie, but for a small and quick development, I would stick with Singleton;)

+3
source

If it is in a class, save the instance in the property:

 class userDB { public $dbCon = false;//because you want to access the instance //from outside the class, I have made the property public function connect() { $con = new PDO("mysql:host=$host;dbname=$db", $user, $pass); $this->dbCon = $con; } } 

To access it outside the class:

$useDBInstance->dbCon;

+1
source
 return $this->con 

return this path from your class and name it that way.

 $this->classObject->con->prepare(); 
0
source

Well, $ con will already be an object, since it creates an instance of a new PDO object. If you are not trying to add functionality to your PDO, wrapping it is pointless.

However, the best way to share your userdb / PDO object (depending on whether you stick with the shell) with other objects is to use Injection Dependency . This is a fancy term for passing your db to any object. Since objects are passed by reference in PHP by default, if you first create your db object, all objects that receive it as an argument to the constructor / method will use the same single instance.

EDIT: Link to Dependency Injection Implementation

EDIT2: DI Explanation in Small Projects -

A normal DI pattern usually requires a special object called a DI container. This is a special object that automatically introduces a dependency in the object that it needs. For small projects, this is unnecessary. A simple version of DI with a low degree of complexity is simple:

 class SomeClass { protected $db; public function __construct($db) { $this->db = $db; } } class SomeClass2 { public function SomeMethod($db) { // do something with the db } } $db = new PDO(/* connection string */); $obj = new SomeClass($db, /* other constructor args */); // or $obj2 = new SomeClass2(/* constructor args */); $obj2->someMethod($db, /* method args */); 

The magic is that since objects are passed by default link in PHP, $ obj and $ obj2 use the same db connection.

The whole idea is not to inflate the scope or encapsulation using the static method and to ensure that the classes and their methods are focused on what they need to work.

Singletones perform the exact opposite. They are accessed using static methods that bypass the scope, and since they are called and not passed, they never appear in the method signatures, so anyone who is not familiar with the code will not know about this hidden requirement. Even Erich Gamma, one of those who helped codify the Singleton template, regrets this :

I am for abandoning Singleton. Its use is almost always the smell of design.

In PHP, where there is no shared memory concept and where scripts are run once for each request, the only reason singleton should be used is easy access to one resource. Because objects are passed by reference, a single instance can be shared by several objects. From there, it's about good design and delegation.

0
source

Checkout my video tutorial + code for an alternative to global PHP variables .

You are doing it wrong. You need to use a static variable if you plan to create your connection in a function and store it there. Otherwise, you will continue to connect to each function call. My tutorial explains this concept of static variables in regular functions.

If this is not clear enough, let me know and I will try to answer your questions.

Here is the code:

 /** * Arguments are none or [$db, [$user, [$pass[, $host]]]]. * * @return PDO */ function PdoDb(){ static $con = null; // I'm explicit :) // Every time you pass Arguments you reconnect if(func_num_args()){ $args = array_pad(func_get_args(), 4, null); list($db, $user, $pass, $host) = $args; if(empty($user)) $user = 'root'; if(empty($host)) $host = 'localhost'; $con = new PDO("mysql:host={$host};dbname={$db}", $user, $pass); } if(empty($con)){ trigger_error('Provide arguments to connect first.', E_USER_ERROR); return null; } return $con; } // First run (provide arguments to connect) PdoDb($db, $user, $pass, $host); PdoDb($db); // Works if you connect root@localhost with no password // From here on (it returns PDO) PdoDb()->DoStuffOfPdo(); 

After connecting, it remains so. But you can connect as you wish by providing arguments.

0
source

Use singlton class semantics

 class connectdb { protected static $_instance = NULL; private function __construct() { } public function getinstance() { if (null === self::$_instance) { self::$_instance = new self(); } return self::$_instance; } public function connect() { $this->connection =new PDO("mysql:host=$host;dbname=$db", $user, $pass); } } 
-2
source

to use a variable inside a class function or an independent function you need to place the global keyword

 $conn=mysql_connect(); function test(){ global $conn; } 

now $conn will be available as part of the test function, and it will be available everywhere if defined at the top of the script. For the class, you also need to do the same, make the class object and declare it global within the function

-4
source

Source: https://habr.com/ru/post/1440766/


All Articles