Public Property unable to access Object Oriented PHP - php

Please look at my databaseClass I Used a public property Called "connection" but I'm unable to access that property other .php files. I'm learning OOP PHP. Please help me.
Here is the other File link http://pastebin.com/0Nh1uc8D
<?php
require_once('config.php');//calling config.php
class Database{
public $connection;//property
//__construct();
public function __construct(){
$this->openDbConnection();
}
//method
public function openDbConnection(){
$this->connection = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
if (mysqli_connect_errno()) {
# code...
die("Database Connection Failed Badly" . mysqli_error());
}else{
echo "DB Connected Successfully.";
}
}
}
//instance of the class
$database = new Database();
?>
Here is my confi.php file code
http://pastebin.com/wQ9BFGf4
Thanks in Advance.

For global access of classes and properties you can use it as static properties and methods:
class Database
{
public static $connection;//property
//method
public static function openDbConnection()
{
self::$connection = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
if (mysqli_connect_errno()) {
# code...
die("Database Connection Failed Badly" . mysqli_error());
}else{
echo "DB Connected Successfully.";
}
}
}
// once "create" connection
Database::openDbConnection();
// and for all other files
var_dump(Database::$connection);

The problem is that $database isn't definied at all by line 16 adminContent.php, if that is indeed all the code for that file in Pastebin.
You're getting distracted by the public property scope, that's working fine as-is. Public properties are definitely accessible from other files not included in other function or class scopes, but only if you've actually required the file that instantiates the $database object in the first place.
Without showing us more code on how adminContent.php is being included from, we can't debug why $database isn't instantiated by line 16.
Use a debugger to trace the code execution flow, or just add echo's or error_log's to both the database instantiation file and to adminContent.php code and run it. I think you'll find that $database isn't instantiated at all, or at least before you're accessing it in adminContent.php

Related

cannot redeclare class dbConnection [duplicate]

This question already has an answer here:
Cannot redeclare class - php [closed]
(1 answer)
Closed 6 years ago.
i recently started learning PDO and OOP to make my websites safer and faster. i am having some issues with OOP in PHP.
i have a folder named res (short for resources) and a folder named classes and an index.php file, in the res folder i have a menu.php file that needs two classes named class.ManageUsers.php and class.ManageNews.php. in both of these files i am including class.database.php, here is the code for that file:
<?php
class dbConnection {
protected $db_conn;
public $db_name = 'red_sec_net';
public $db_user = 'root';
public $db_pass = '';
public $db_host = 'localhost';
function connect(){
try{
$this->db_conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name;",$this->db_user,$this->db_pass);
$this->db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $this->db_conn;
$this->conn = null;
}catch(PDOException $e){
die('failed to connect to database');
}
}
}
?>
now in the index.php file i need class.ManageUsers.php so i include it just before i include menu.php but when i go to that page i get this error:
Cannot redeclare class dbConnection in C:\wamp64\www\redsec\classes\class.database.php on line 3
the people i consulted said i should close the connections so i did that using
$this->link = null; and all the other variables that contained anything related to the connection after i do return what i need.
this is my constructor method:
class ManageUsers {
public $link;
function __construct(){
$db_connection = new dbConnection();
$this->link = $db_connection->connect();
return $this->link;
$this->link = null;
}
}
all my attempts have failed and i am starting to pull my hair out any help appreciated
i believe the error is happening in the constructor method when i do $db_connection = new dbConnection();
When your PHP app loads, the interpreter comes across the same class declaration more than once.
Try this:
include_once or require_once (if multiple inclusions of the same file happen)
Probably this could be a duplicated:
Cannot redeclare class - php

Best way to implement database connection in php

I don't know my method is correct for connecting to the database in php.
Here is the method i am used.
1.created a db_functions.php file.
db_functions.php
/*----for connecting db----*/
function db_connect(){
$connect=new PDO('mysql:host=localhost;dbname=keralalotteryapp','root','');
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $connect;
}
function get_student_data(){
$con=db_connect();
//rest of my query
}
function get_marks($id){
$con=db_connect();
//rest of my query
}
2.In every my page i've included this and call the functions like this way
<?php
require 'db_functions.php';
get_student_data();
get_marks($id);
?>
But everytime call the functions get_student_data() and get_marks() it will again call the db_connect function.
So this is right way to do this?
Create a connection class in a Connection.php file :-
class Connection{
public static $PDO =null;
public static function getConnectionInstance()
{
try{
$PDO = new PDO('mysql:host=localhost;dbname=keralalotteryapp','root','');
return $PDO;
}catch(PDOException $e)
{
die($e->getMessage());
}
}
}
or use this class any other php file like that :-
require_once './Connection.php';
function __construct() {
$this->dbh = Connection::getConnectionInstance();
}
create construct or call static method of connection call
There are many ways to manage database connections, I've seen a global connection object, I've seen some people do connection factories, at the end of the day it really comes down to your needs in your specific application.
That being said, if you have the support for it, I have always been a fan of a closure-based setup as I find it becomes easy to write clean code.
function execute_in_db_context($callback) {
$connect=new PDO('mysql:host=localhost;dbname=keralalotteryapp','root','');
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$callback($connect);
$connect=null; //cleanup because we can
}
execute_in_db_context(function ($db_connection) {
//blah blah
});

How to acess Private function of another class in PHP [duplicate]

This question already has answers here:
What is the difference between public, private, and protected?
(16 answers)
Closed 7 years ago.
I have a dbHandeller.php file . as follow
class dbHandeler {
var $conn;
public function __construct(){
$this->initiatedb();
}
private function initiatedb(){
//Details of the Databse
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "xxxxxx";
// Create connection
$this->conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$this->conn) {
die("Connection failed: " . mysqli_connect_error());
}else
return $this->conn;
}
private function sql_query($query){
}
}
Then I have donation.php and it extends the DB class
function __autoload($class_name) {
include $class_name . '.php';
}
class donation extends dbHandeler{
public function __construct(){
$dbObj = new dbHandeler();
$dbObj->initiatedb();
}
public function putDonation(){
var_dump($_POST);
}
public function getDonation(){
}
}
When I try to access the donation class I am getting following error
<br />
<b>Fatal error</b>: Call to private method dbHandeler::initiatedb() from context 'donation' in <b>C:\xampp\htdocs\templeform\api\donation.php</b> on line <b>13</b><br />
error
The "private" access specifier is meant to be available within the class it is defined only, you cannot call it from outside the class it is defined in, even from a child class. You can maybe use the "protected" access specifier instead which will be available to the child classes as well but not the other classes. Hope this helps.
If the method is private, there is a reason, why the method is private. A private functions could only be called inside the class. If the method should be available in inherited classes, you should mark the function protected.
If the function should be accessible from everywhere, it must be public.
If you want to change the accessibility of the function, you could do so with ReflectionMethod::setAccessible - but doing this is most often a good indicator for a bad design.
$method = new ReflectionMethod('dbHandeler', 'sql_query');
$method->setAccessible(true);
If you dont want to change the accessibility, you could also use reflection to invoke the method directly, which might be the better option.
Nevertheless you should really think about you design. If this is your own class, why don't you just mark the function public or protected?

One connection for ALL ,OOP PHP

struggling to grip the varying levels of variables in OOP PHP. I want to have one connection file which can be accessed from all classes and functions through out my project. I include 'config.php' but the $mysql variable cannot be found. Any help greatly appreciated;
I have a file
config.php
public $mysqli = new mysqli('localhost', 'usernameEG', 'passwordEG', 'databaseEG');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
and a few class files
class.User.php
<?php
class User {
private $mysqli = null;
function __construct(){
//=========
//include config.php here?
}
function myProfile($Id){
$stmt = $this->mysqli->prepare("SELECT First_Name, Last_Name, Email, DateJoined FROM members WHERE Id = ? ");
$stmt->bind_param('i',$Id);
$stmt->execute();
$stmt->bind_result($fname,$lname,$email,$date);
$stmt->store_result();
$stmt->fetch();
echo "<p>User#: ".$Id."</p>";
echo "<p>First Name: ".$fname."</p>";
echo "<p>Last Name: ".$lname."</p>";
echo "<p>Email: ".$email."</p>";
echo "<p>Date Joined: ".$date."</p>";
$stmt->close();
}
function example(){
EXAMPLE CODE HERE WILL ALSO NEED TO BE ABLE TO USE SAME CONNECTION
}
}
So rather than a singleton approach as hinted at in the other answer. Let me offer you a dependency injection approach. For a lot of experienced developers, dependency injection is a preferred approach, as it allows the class receiving the dependency to have looser coupling to the dependency (for example, you don't need to even know the name of the class for instantiating the dependency like you would with a singleton approach). You just need to know that the dependency being passed meets some interface requirement (i.e. it implements some interface or is a certain type of class).
So that would look more like this:
class User {
protected $mysqli = null;
// other properties
public function __construct(mysqli $mysqli) {
$this->mysqli = $mysqli;
// other constructor operations
}
// other methods
}
So what is happening here? Here you enforce the requirement to pass an object of type mysqli when instantiating this class. This could be a mysqli object or perhaps even your own custom class which extends mysqli, the User class doesn't care, so long as all mysqli class methods are implemented
Usage could be like
require('/path/to/db_config.php'); // an include which creates a mysqli object or provides a factory for one, or whatever
$user = new User($mysqli);
$user->foo(); // do something
Interestingly enough, you might at times see use of singelton pattern along with dependency injection. So say you had a mysqli_singleton_factory class with singleton functionality to provide you the single instantiated mysqli object. The usage might look like this:
require('/path/to/db_config.php'); // an include which provides a singleton
$user = new User(mysqli_singleton_factory::get_instance());
$user->foo(); // do something
$other_class = new other_class_requiring_mysqli(mysqli_singleton_factory::get_instance());
$other_class->bar(); // do something
Here you have both guaranteed that you only have one instantiated mysqli object during script execution AND you have decoupled your User class from having to do any instantiation of the object itself.
For reference, a singleton pattern may look like this:
class mysqli_singleton_factory {
protected static $mysqli = null;
protected function __construct() {
// assume DB connection setting have been pre-defined as constants somewhere
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// make sure connection worked
if($mysqli->connect_error) {
throw new Exception(__METHOD__ . ' at line ' . __LINE__ . ' failed with: ' . $mysqli->connect_error);
}
self::mysqli = $mysqli;
}
public static function get_instance() {
if (false === self::mysqli instanceof mysqli) {
self::__construct();
}
return self::mysqli;
}
}
I've done this a number of times previously and I have found that it is easy to implement "singleton-like" class to serve as a database connector which then can be referenced by any object in the application.
config.php
Config.php is where the credentials are set and the database class is actually constructed.
$dbHost = 'localhost';
$dbUser = 'someUser';
$dbPass = 'somePass';
$dbSchema = 'someSchema';
Database::$db = new MySQLi($dbHost, $dbUser, $dbPass, $dbSchema);
classes.php
classes.php is where my classes are defined, which is kept separate from the rest of the code.
class Database {
public static $db;
}
class User {
...
function example()
{
$stmt = Database::$db->prepare('SELECT TRUE');
...
}
}
index.php
index.php is the entry point for the app, and is used to handle the request and exhibit the desired behavior using the supplied classes.
require_once('classes.php');
require_once('config.php');
/* Application Goes Here */
This ensures that all objects in my project use the same connection, I only have to invoke it once and I don't have to mess about with scope too much.

Trouble connecting to the database

I'm trying to connect to 2 databases. One of them is a remote database. Once i connected to the remote database i had trouble with the one that existed, it gave me 'supplied argument is not valid ' on mysql_fetch_array() . So i changed my database class a bit and tried to make it work. But i still get errors :(. Its not grabbing $connection variable.
i get "undefined variable connection".
this is my connection class. Please help me out. Appreciate your help.
global $connection;
class Database{
function __construct()
{
$this->open_connection();
}
public function open_connection()
{
$connection = $this->connection= mysql_connect(SERVER,UNAME,PASSWORD);
if(!$this->connection)
{
return false;
}
if(!mysql_select_db(DB_NAME,$this->connection))
{
return false;
}
return true;
}
public function close_connection()
{
mysql_close($this->connection);
}
//open_connection();
}
$database = new Database();
and in another page:
$result=mysql_query($query,$connection);
while ($rec = mysql_fetch_array($result)) ... etc
p.s all constants and other variables are correct.
Using a global variable in a class is like death.
You could provide a class field for the connection link
$this->connection = mysql_connect(...);
And outside your class
$result = mysql_query($sql, $object->connection);
I'd also suggest you to use the existing mysqli class.
Hmm... Well, it looks like you are getting an undefined error thrown because you are calling global $connection at the top of the class file, and it hasn't been assigned a value.
It looks like you are establishing $connection inside of the open_connection() method... Are you establishing $connection in some included file that you haven't mentioned?
Try removing the first line of code, perhaps?
the "global $connection;" MUST be inside "open_connection" method or use #peipst9lker method

Categories