i have class called dbconnection. I want to call this connection function in the constructor. Usually in Java, i just declare:
private FileName variable = new Filename();
and assign the variable.logOn on any functions.
But now, in authenticate php class, i couldn't do that. So i think i can execute the connection in constructor, I've tried:
public function __construct(){
$conn = new Database();
}
but i couldn't access the $conn var because it's not global variable.
Another method i use is placing below code outside any function.
public $conn = new Database();
but it shows an error.
How properly calling the variable or executing another function from another class in php?
thanks.
You need to make $conn a field, and $this->conn to initialize it:
public $conn; // declare $conn field
public function __construct () {
$this->conn = new Database(); // initialize field
}
Do you mean like this?
public $conn;
public function __construct () {
$this->conn = new Database();
}
Related
I'm starting to learn how to use OOP within PHP and so far I want to create a Database class that looks like this:
class Database{
//Database connection variables
private $DBHost = "localhost";
private $DBUser = "username";
private $DBPass = "password";
private $DBName = "database3";
public $DBCon;
public function __construct(){
$this->DBCon = new mysqli($this->DBHost,$this->DBUser,$this->DBPass,$this->DBName);
}
public function con(){
return $this->DBCon;
}
public function __destruct(){
$this->DBCon->close();
}
}
And I'm trying to interact with that class from another one called Application:
include('Database.php');
class Application{
public $DB;
public function __construct() {
$DB = new Database();
}
public function InsertName($Username){
var_dump($this->DB->con());
if($this->DB->con()->query("INSERT INTO Test (name) VALUES ($Username);") === TRUE){
echo "Okay";
}else{
echo "Error";
}
}
}
But I get the error Call to a member function con() on a non-object
As a side note, is this an appropriate way to interact with a database in OOP?
Inside the Application class constructor, $DB is being assigned new Database().
This variable is considered a local variable in this case with its scope being the constructor function itself.
To properly assign the new database object to the public $DB property, you will need to access it via the object's $this reference.
public function __construct() {
$this->DB = new Database();
}
This way you will be able to access the proper assigned public property throughout your remaining class methods.
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.
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);
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);
}
}
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);