How can we access a one class object in another class? - php

I still have not been able to figure this out. How can we access a one class object in another class?
I am using the below code but I am getting and error:
class ListofRecord{
var $db;
function __construct(){
$db = global $db;
}
function record(){
$record = $this->db->SelectQuery("SELECT * FROM user order by UID ASC");
return $record;
}
}

You need to refer to the global $db variable first and then use it in a statement. You also have a minor syntax error in your constructor. You forgot to use the $this keyword when referring your your $db property.
function __construct(){
global $db
$this->db = $db;
}
It also is a better practice not to use global variables and instead pass any variables that you need as parameters to your method call. In this case it is your constructor:
function __construct($db){
$this->db = $db;
}
$list_of_record = ListofRecord($db);

Related

Class not printing variable

Im trying to understand objects & classes. But Im having a problem. Im trying to pass a variable from a class into another class.
Why Im doing this is mostly because I want to understand more how classs work but also for future where Im gonna need to send database connection into classes.
Here is my code simplified for the problem:
class databaseConnection
{
public function connect(){
return "localhost";
}
}
class like
{
private $database;
public function __construct(){
$this->database = databaseConnection::connect();
}
public function addLike()
{
return $database;
}
}
$obj = new like;
echo $obj->addLike();
But this doesn't show anything. What i thought the results would be is echo "localhost";
Why isn't this working?
connect is not a static method, you should either change it to static or create an instance.
// if you use databaseConnection::connect();
public static function connect(){
or
$db = new databaseConnection;
$this->database = $db->connect();
And you also need to change
public function addLike()
{
// use $this to access object property
return $this->database;
}
You are calling databaseConnection::connect() as a static method. Modify it to:
public static function connect(){ }
Edit - as #Shankar Damodaran pointed, also add:
public function addLike()
{
return $this->database;
}
First of all you should really follow convention and start naming classes StartingWithCapitalLetter.
Secondly, "::" operator is used to call static methods (to put it simply - you don't have to create object of a class to call them, if they are public).
Normally, to call object's method you use operator "->", like $object->method(arguments);
So in your case, you need to first create an object of your databaseConnection class (because you can't call methods on not-initialized methods) and then call "connect" on it, like that:
$connection = new databaseConnection();
$database = $connection->connect();
To pass a parameter, you need to modify the method declaration
public function connect($parameter){
return "Connecting to " ... $parameter;
}
and call it with
$database = $connection->connect($parameter);
On a sidenote, you should really use parenthesis when creating objects of a class, like:
$obj = new like();
echo $obj->addLike();
Also, as deceze pointed out, you need to access class variable using $this instead of accessing local method variable:
public function addLike()
{
return $this->database;
}
public function addLike()
{
return $this->database;
}
$database and $this->database are two different variables. $database is a local function variable which does not exist, it's not the object property you set before.

What to use instead of global in php

Is there any other way instead of using global everytime I need to access a global variable inside a function?
$db = new ezSQL_mysql("root", "", "payroll", "localhost");
class employee{
function get_emp(){
global $db;
}
}
In normal global-scope functions, either use the global keyword, or $GLOBALS['db'] superglobal array (which is preferable for readability). The other alternative is to pass the global variable into the function as a parameter.
In your class, the best method is dependency injection. Your class constructor receives the $db as a parameter, which makes it available to all class methods:
// $db was created at global scope
$db = new ezSQL_mysql("root", "", "payroll", "localhost");
class employee {
public $db;
// $db already created in your script is passed as a dependency
// to the class constructor
public function __construct($db) {
$this->db = $db;
}
// Access it as $this->db inside the class
public function get_emp() {
do_something($this->db);
}
}

PHP class scope

I have several classes in an application that I am currently building, and I want to have one access some of the other's member functions but i can't seem to do it.
The first class is called MySQLDB:
class MySQLDB{
public $connection;
function __construct(){
//connects to database
}
function login($username, $password){
//queries database...
}
}
Then I have a class called Session:
class Session{
//variables
//constructor
function processlogin($username, $password){
$database->login($username, $password);
}
Then after this I have two class declarations:
$database = new MySQLDB();
$session = new Session();
No matter where i put these statements in relation to the classes I still get the same error:
PHP Notice: Undefined variable: database in C:\inetpub\wwwroot\cmu\include\session.php on line 52
PHP Fatal error: Call to a member function login() on a non-object in C:\inetpub\wwwroot\cmu\include\session.php on line 52
I have seen some suggestions that would suggest putting the new database object inside the Session class declaration but I want to avoid doing so because I use the database class several other places in the code and I don't want to open up multiple connections to the database.
since you want to have acces on a globally set variable, you can either gain access to it with global:
function processlogin($username, $password){
global $database;
$database->login($username, $password);
}
or use the variable as a parameter for the contructor and remember the database object reference in the class Session:
class Session{
private $database;
function __construct($database){
$this->$database = $database;
}
function processlogin($username, $password){
$this->database->login($username, $password);
}
}
and then you call:
$database = new MySQLDB();
$session = new Session($database);
this comes in handy, if you use more functions afterwords, that also need access to the database object.
you could pass a reference to the MySQLDB instance in the Session constructor.
class Session{
public $db;
function __construct(&$db=null){
if($db == null)
$this->db = new MySQLDB();
else
$this->db = $db;
}
// ....
}
$database = new MySQLDB();
$session = new Session($database);
You are creating two global variables. If you're doing such thing, you need to declare variables you want to use in function with "global" keyword:
function processlogin($username, $password){
global $database;
$database->login($username, $password);
}
Despite this will work, I highly recommend reading about Dependecy Injection mechanism in which you'd pass $database variable as a parameter to processlogin() method, or set it as a private member of that class in constructor / setter. That way database connection will be interchangeable and you'll get more flexibility in your code.
$database is not defined inside processlogin nor passed as parameter, hence the function has no access to it.
You could pass it as constructor parameter to Session:
class Session {
private $db;
public function __construct($database) {
$this->db = $database;
public function processlogin($username, $password){
$this->$db->login($username, $password);
}
}
$database = new MySQLDB();
$session = new Session($database);

Objects in PHP including other objects

I think the title is right but please correct me if It is mis-leading.
The problem: I have a class which wants to use the DB class, now instead of having to "global $db;" in every method I wish to use the DB object I want to be able to place the object reference in my class properties.
Still following? OK here goes:
class user
{
private $id = 0;
private $name = NULL;
private $password = NULL;
private $db;
function __construct()
{
$this->load_db();
}
private function load_db()
{
global $db;
$this->$db =& $db;
}
I get an error "Object of class db could not be converted to string" which is annoying as I can't figure out how to set the var type in PHP...
Now my question is two fold:
1) How do I fix this.
or
2) Is there a better way of doing it as this feels really "kack-handed".
Thanks in advance,
Dorjan
edit: Just to make sure I'm clear I do not want to make multiple instances of the same DB object. At least I believe this to be a good practice ^,^
If you're using $this, you only need one dollar sign. So $this->db.
private function load_db()
{
global $db;
$this->db =& $db;
}
Also if you are using php 5 you dont need to use the =& operator because objects are implicitly passed by reference. Secondly, you should inject $db into the constructor or fetch it from a Registry object instead of using global.
You should better do
class User
{
private $id = 0;
private $name = NULL;
private $password = NULL;
private $db;
function __construct($db=null)
{
$this->db = $db;
}
}
Note that you don't put a $ before variable names if you access properties via $object->. That is were the error comes from.
To use a global inside a class method is really bad practice as you somehow tie your class to that global variable. Better pass it as a parameter to the constructor or a method.
Later you can instantiate the class with
$user = new User($db)
Also note that class names by convention start with a capital letter.
This:
$this->db
Inject the db instance through the constructor
public function __construct($db)
{
$this->db = $db;
}
Yopu'll want to use something called dependency injection. This is where you "inject" an object into another object to do whatever it is the object does. In this case do database stuff
class user
{
private $id = 0;
private $name = NULL;
private $password = NULL;
private $db;
function __construct($database_object)
{
$this->load_db();
$this->$db = $database_object;
}
public function do_db_stuff()
{
$this->$db->doStuff();
}
$db = new Mysql()
$user = new User($db);
$user->do_db_stuff();

Passing Objects into PHP constructor error

Is it possible to pass an object into the constructor of a PHP class, and set that object as a global variable that can be used by the rest of the functions in the class?
For example:
class test {
function __construct($arg1, $arg2, $arg3) {
global $DB, $ode, $sel;
$DB = arg1;
$ode = arg2;
$sel = $arg3;
}
function query(){
$DB->query(...);
}
}
When I try to do this, I get a "Call to a member function on a non-object" error. Is there anyway to do this? Otherwise, I have to pass the objects into each individual function directly.
Thanks!
You probably want to assign them to values on $this.
In your constructor, you'd do:
$this->DB = $arg1;
Then in your query function:
$this->DB->query(...);
This should similarly be done with the other arguments to your constructor.
$this in an instance context is how you reference the current instance. There's also keywords parent:: and self:: to access members of the superclass and static members of the class, respectively.
As a side-note...
Even thought this isn't required, it is generally considered best to declare member variables inside the class. It gives you better control over them:
<?php
class test {
// Declaring the variables.
// (Or "members", as they are known in OOP terms)
private $DB;
protected $ode;
public $sel;
function __construct($arg1, $arg2, $arg3) {
$this->DB = arg1;
$this->ode = arg2;
$this->sel = $arg3;
}
function query(){
$this->DB->query(...);
}
}
?>
See PHP: Visibility for details on the difference between private, protected and public.
you can do it pretty easily by storing the argument as a property of the object:
function __construct($arg1, $arg2, $arg3) {
$this->db = arg1;
}
function f()
{
$this->db->query(...);
}
let's say you have a db object
$db = new db();
and another object:
$object = new object($db);
class object{
//passing $db to constructor
function object($db){
//assign it to $this
$this-db = $db;
}
//using it later
function somefunction(){
$sql = "SELECT * FROM table";
$this->db->query($sql);
}
}

Categories