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

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?

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

PDO database connection can not be used in other classes, but others can? [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 6 years ago.
I've been working on a databaseHandler php class, which should connect to the database and then be usable in other PHP files, atleast this was the plan. I've come across the problem that it cannot use any PDO related functions in my PHP class, i've tried checking if it was null, or not set at all (but it was) and i've also tried using a dummy function that just echos something which was to test if the class isn't undefined in others.
<?php
class databaseHandler {
private $db;
private static $instance;
function __construct() {
$this->buildDatabaseConnection();
}
public static function getInstance() {
if(!self::$instance) {
self::$instance = new databaseHandler();
}
return self::$instance;
}
private function buildDatabaseConnection() {
require 'dbconfig.php';
try {
$this->db = new PDO("mysql:host=" . HOST . ";dbname=" . DATABASE . ";charset=utf8", USER, PASSWORD);
if(isset($this->db)) {
if(!is_null($this->db)) {
echo "isn't null";
}
}
} catch(PDOException $e) {
$e->getMessage();
}
}
public function getConnection() {
return $this->$db;
}
public function getSomeShit() {
echo "some shit";
}
}
?>
The problem might be with the getConnection() php function, does it actually return the PDO object here? Because the main problem lays with the fact that i get this error when i use my getConnection function in other classes:
Notice: Undefined variable: database in F:\Websites\DevProject\php\functions.php on line 69
Fatal error: Uncaught Error: Call to a member function prepare() on null in F:\Websites\DevProject\php\functions.php:69 Stack trace: #0 F:\Websites\DevProject\php\functions.php(51): register('qwe', 'sdasd', 'asdasd', 'asdas', '01-01-1970') #1 F:\Websites\DevProject\register.php(123): datelessRegister('qwe', 'sdasd', 'asdasd', 'asdas') #2 {main} thrown in F:\Websites\DevProject\php\functions.php on line 69
and line 69 would be this:
$stmnt = $database->prepare("SELECT $username, $email FROM " . USERTABLE);
Where the $database variable is the class instance:
$database = databaseHandler::getInstance();
If i try to var_dump it in my registration php file, it'll tell me this:
object(databaseHandler)#1 (1) { ["db":"databaseHandler":private]=> object(PDO)#2 (0) { } }
However, when i use it inside of my function, it will say it is 'NULL', why is it null in a function but defined globally?
All the errors relate to the object, and in there it tells me the pdo is undefined (i've tried checking if it was null, but it wasn't!)
Any help would be great, thanks in advance.
In the return statement of getConnection method you should write the class variable without $:
return $this->db;
Also, you must do the queries on the PDO connection instead of your database handler class, so $database = databaseHandler::getInstance(); should be
$database = databaseHandler::getInstance()->getConnection();
or you can simply use the __call magic method to keep your code as it is right now:
public function __call($method, $args)
{
return call_user_func_array(array($this->db, $method), $args);
}
Also, to clarify how to use this class, you should call it inside every method you need the database to be used, not only once on the top of your file, because defining it there it will not be available inside your methods/functions unless you don't use the global statement to import the variable. However usage of the global variable is not encouraged and it is considered as a bad practice. An example on how to use the database would be:
public function doSomething()
{
$db = databaseHandler::getInstance()->getConnection();
$db->prepare(....);
}
public function doSomethingElse()
{
$db = databaseHandler::getInstance()->getConnection();
$db->prepare(....);
}
If you know there are many methods inside your class that uses the database then you can define it as a class variable and set the db instance in the constructor.
You seem to be having issues with scopes.
$database = databaseHandler::getInstance();
function doSomething()
{
// $database is not defined in this scope
$database->getConnection()->prepare(/* ... */);
}
You have to declare it as part of the global scope
function doSomething()
{
global $database;
$database->getConnection()->prepare(/* ... */);
}
The problem seems to be in the getConnection() function. Since $db is field you must do.
return $this->db;
However this is a very complex class structure for a simple problem.
You can directly extend your class from PDO
class DatabaseHandler extends PDO {
function __construct() {
parent::__construct('mysql:host=host_name;dbname=db_name', 'user_name', 'password');
parent::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
}
And create an object of this whenever you want to do database transaction.
$db = new DatabaseHandler();
$stmt = $db->prepare(".....");
$stmt->execute();

How do I use multiple classes in PHP

I'm very new to oop in php, so far i'm using multiple classes that I made in one php file, such as:
class Style {
//stuff
}
class User {
//other stuff
}
And many more, yet i'm having an issue on how to connect to mysql within these classes, if I use $db = new Mysqli(); how will I be able to make queries from inside classes? what if i'm trying to make my own connector class like so:
class Connection extends mysqli {
public function __construct($host, $user, $pass, $db) {
parent::__construct($host, $user, $pass, $db);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
}
}
How can I be able to make queries from within different classes? Or what's a better way of using oop in php correctly? with multiple classes to organize different parts of code?
Any help or tips will be appreciated, thanks. What about using PDO? does that make everything easier?
class Style {
public function __construct($conn) {
$this->conn = $conn;
//use $this->conn in the class
}
}
$db = new Mysqli();
$style = new Style($db);
I think the first example is the preferred method, however you could create a simple registry class and use that to store a $db object etc.
If possible I would probably use PDO but that doesn't solve this issue.
Since you are extending the mysqli class you will have access to the functions as you would if you instantiated that class by itself (so long as those functions aren't private). Some folks though (including myself) will instantiate the DB connection in their own custom class with a database connection, then inject that class into classes that need it.
class MyDatabase {
private $this->dbi;
public function __construct() {}
public function connectDB($host, $user, $pass, $db)) {
//You can do this in the constructor too, doesn't have to be its own function
$this->dbi = new mysqli($host, $user, $pass, $db);
}
public function getDBI() {
return $this->dbi;
}
}
You can add all the functions you want to your own class (or an extended class), you can also have any class that needs a database extend your DB class. But that isn't really preferred (each class will have a different db class/connection). The easiest is probably to import your DB connection into your class. Either through the constructor or another function;
class MyClass {
private $this->database;
public function __construct($db) {
$this->database = $db->getDBI();
}
public function query($q) {
//Of course, clean your data first, and best practices use prepared statements
$result = $this->database->query($q);
return $result;
}
}
Then make your database connection and inject it into your class.
$db = new MyDatabase();
$db->connectDB('localhost', 'username', 'password', 'mydb');
$class = new MyClass($db);
$resultSet = $class->query("SELECT * FROM MyTable"); //Obviously anything the user could add here is to not be trusted.
using PDO will give you a lot of functions and flexebilty and it has many drivers built-in.
to make what you are trying to do here is a sample :
STEP 1 :
Make a Main class that will handle your database :
class app extends PDO {
protected $database_hostname = "localhost";
protected $database_username = "root";
protected $database_password = "";
protected $database_name = "testdb";
protected $database_type = "mysqli";
public function __construct() {
try {
parent::__construct($this->database_type . ':host=' . $this->database_hostname . ';dbname=' . $this->database_name, $this->database_username, $this->database_password, array(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION));
} catch (PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
}
STEP 2 :
then you need to initilze a globale variable as your Database :
$db= new app() ;
STEP 3 :
include a local variable to handle database in the other classes :
class User{
public $db ;
}
STEP 4 :
in the constructor of the other classes ( user for exemple ) you need to pass the local variable by reference to the globale variable :
class User{
public $db ;
public function __construct(){
global $db;
$this->db =& $db;
}
}
STEP 5 :
then if you want to execute a request from inside a class you do it by the local variable :
$this->db->query("SELECT * FROM user");
and from the outside just by using : $db->query("SELECT * FROM user");
I hope that helped !

PHP: Database Connection Class Constructor Method

I'm new to OOP. Originally I was defining variables and assigning values to them within the class and outside of the constructor, but after an OOP lesson in Java today, I was told this is bad style and should be avoided.
Here is my original PHP database connection class that I mocked-up:
class DatabaseConnection {
private $dbHost = "localhost";
private $dbUser = "root";
private $dbPass = "";
private $dbName = "test";
function __construct() {
$connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass)
or die("Could not connect to the database:<br />" . mysql_error());
mysql_select_db($this->dbName, $connection)
or die("Database error:<br />" . mysql_error());
}
}
Is the above considered okay? Or is the following a better way?
class DatabaseConnection {
private $dbHost;
private $dbUser;
private $dbPass;
private $dbName;
function __construct() {
$this->dbHost = "localhost";
$this->dbUser = "root";
$this->dbPass = "";
$this->dbName = "test";
$connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass)
or die("Could not connect to the database:<br />" . mysql_error());
mysql_select_db($this->dbName, $connection)
or die("Database error:<br />" . mysql_error());
}
}
What should I be focusing on to make sure I am understanding OOP correctly?
First of all: this is pointless.
You are creating an object wrapper for the 10+ year old mysql_* function. This php extension is no longer maintained and the process of deprecation has already begun. You should not use this API for any new projects in 2012.
Instead you should learn how to use PDO or MySQLi and work with prepared statements.
That said .. lets take a look at your code:
Constructor should receive all the parameters required for creating new instance, parameters should not be hard-coded in the class definition. What if you need to work with two databases at the same time ?
When connection is created, it should be stored in object's scope variable. Something along the lines of $this->connection = mysql_conn.... Instead you store it in local variable, which you "loose" right after constructor is done.
You should not use private variables for everything. They are not visible to classes which would extend your original class. Unless it is intentional, you should choose protected for this.
The or die('..') bit most go. Do not stop the whole application if connection fails. Instead you should throw an exception, which then can be handled outside of the constructor.
Well, it's not going to run quite yet. You need to change your variables so that they match your connection params:
$dbHost = "localhost";
Should be
$this->dbHost = 'localhost';
I normally don't put my login params inside of the class at all. I would pass them into the constructor when the object is created. Use an outside config file so you can actually use this class on more than one build. :)
Update::
Okay, so here are a few little OOP configuration gold-nuggets that help you build a dynamic Database class.
Check out http://redbeanphp.com/ It will allow you to do a psuedo ORM style of data modelling. Super easy to install, and ridiculously easy to get your database up and running. http://redbeanphp.com/manual/installing
Create a configuration file that contains things like constants, template setups, common functions, and an AUTOLOADER Configuration files are key when working in version controlled environments. :)
Build your Database class as an abstract class http://php.net/manual/en/language.oop5.abstract.php
abstract class Database
{
public function update()
{
}
public function deactivate()
{
}
public function destroy()
{
}
//etc.
}
class MyAppObject extends Database
{
}
Put all of your class files into a library folder, and then put your configuration file into that library. Now, to make your life easier you can use an autoloader function to bring your classes to life whenever you need them, without having to include any specific class. See below:
//note: this is never explicitly instantiated
//note: name your files like this: MyAppObject.class.php
function my_fancypants_autoloader( $my_class_name )
{
if( preg_match( "%^_(Model_)%", $my_class_name ) ) return;
require_once( "$my_class_name.class.php" );
}
spl_autoload_register( 'my_fancypants_autoloader' );
Now all you have to do is include one configuration file in your .php files to access your classes.
Hope that points you in the right direction! Good luck!
Since your are only using them into the __construct method, you don't need them as class attributes. Only the $connection has to be kept for later use imho.
It might be much much better to not give any default values to those arguments but let them being set from the outside.
$db = new DatabaseConnection("localhost", "user", "password", "db");
They are plenty of PHP tools for that already, find them, read them and learn from that. First of all, use PDO and what is true in Java isn't always true in PHP.
The latter is probably better, but with an adjustment: pass some arguments to the constructor, namely the connection info.
Your first example is only useful if you've got one database connection and only if you're happy hard-coding the connection values (you shouldn't be). The second example, if you add say, a $name parameter as an argument, could be used to connect to multiple databases:
I'm new to OOP. Originally I was defining variables and assigning values to them within the class and outside of the constructor, but after an OOP lesson in Java today, I was told this is bad style and should be avoided.
class DatabaseConnection {
private $dbHost;
private $dbUser;
private $dbPass;
private $dbName;
function __construct($config) {
// Process the config file and dump the variables into $config
$this->dbHost = $config['host'];
$this->dbName = $config['name'];
$this->dbUser = $config['user'];
$this->dbPass = $config['pass'];
$connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass)
or die("Could not connect to the database:<br />" . mysql_error());
mysql_select_db($this->dbName, $connection)
or die("Database error:<br />" . mysql_error());
}
}
So using this style, you now have a more useful class.
Here is mine and it works rather well:
class Database
{
private static $_dbUser = 'user';
private static $_dbPass = 'pwd';
private static $_dbDB = 'dbname';
private static $_dbHost = 'localhost';
private static $_connection = NULL;
/**
* Constructor
* prevents new Object creation
*/
private function __construct(){
}
/**
* Get Database connection
*
* #return Mysqli
*/
public static function getConnection() {
if (!self::$_connection) {
self::$_connection = #new mysqli(self::$_dbHost, self::$_dbUser, self::$_dbPass, self::$_dbDB);
if (self::$_connection -> connect_error) {
die('Connect Error: ' . self::$_connection->connect_error);
}
}
return self::$_connection;
}
}
By making the __construct empty, it prevents a new class being instantiated from anywhere. Then, make the function static so now all I need to do to get my connection is Database::getConnection() And this is all in an include file, in a password protected folder on the server and just included with each class file. This will also check to see if a connection is already open before attempting another one. If one is already established, it passes the open connection to the method.
<?php
class config
{
private $host='localhost';
private $username='root';
private $password='';
private $dbname='khandla';
function __construct()
{
if(mysql_connect($this->host,$this->username,$this->password))
{
echo "connection successfully";
}
}
function db()
{
mysql_select_db($this->$dbname);
}
}
$obj=new config();
?>

How to use an outside variable in a PHP class?

I have config.php with this...
$dbhost = "localhost";
I want to be able to use the $dbhost variable inside a class.
User.class.php
include 'config.php';
class User {
private $dbhost = ???
}
There's a couple other questions like this, but they were for some other specific uses, and I guess it's just a basic thing that I can't really find anything else about it on the web.
UPDATE: Wow, thanks for all the help everybody. New to this site, but I might just stick around and give back where I can.
You could use a global variable, defining a constant would be better, but using a setter/getter method is best. When you are using a class, any outside resource that it uses should be passed to it. This design patter is called dependency injection if you want to research it further.
In this example, I've combined the setter and getter into a single method, and included the ability to set the value when you first create the instance, using a constructor:
class User
{
private $host = null;
public function host($newHost = null)
{
if($newHost === null)
{
return $this->host;
}
else
{
$this->host = $newHost;
}
}
function __construct($newHost = null)
{
if($newHost !== null)
{
$this->host($newHost);
}
}
}
//Create an instance of User with no default host.
$user = new User();
//This will echo a blank line because the host was never set and is null.
echo '$user->host: "'.$user->host()."\"<br>\n";
//Set the host to "localhost".
$user->host('localhost');
//This will echo the current value of "localhost".
echo '$user->host: "'.$user->host()."\"<br>\n";
//Create a second instance of User with a default host of "dbserver.com".
$user2 = new User('dbserver.com');
//This will echo the current value of "dbserver.com".
echo '$user2->host: "'.$user2->host()."\"<br>\n";
For something like a db host, use a constant:
// define it first
define('DBHOST', 'localhost');
// then anywhere you can use DBHOST:
class User {
function __construct() {
echo DBHOST;
}
}
http://php.net/manual/en/language.constants.php
several ways I think.
First pass it to the class constructor:
include 'config.php';
class User {
private $dbhost;
function __construct($dbhost){
$this->dbhost=$dbhost;
}
}
$user= new User($dbhost);
Or use a setter:
include 'config.php';
class User {
private $dbhost;
function setDbhost($dbhost){
$this->dbhost=$dbhost;
}
}
$user= new User();
$user->setDbhost($dbhost);
Or using CONSTANTS:
define('DBHOST', 'localhost');
class User {
private $dbhost;
function __construct(){
$this->dbhost=DBHOST;
}
}
OR using global:
include 'config.php';
class User {
private $dbhost;
public function __construct() {
global $dbhost;
$this->dbhost=$dbhost;
}
}
If you are planning to use variables (and not constants), then use the following code.
In config.php
$dbhost = "localhost";
In User.class.php
include 'config.php';
class User {
global $dbhost;
}

Categories