简体   繁体   中英

Public Property unable to access Object Oriented 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM