Variable aus einer include_once Datei übernehmen geht nicht

loddarmattheus

Erfahrenes Mitglied
Hallo,

ich habe ein kleines Problem mit zwei Dateien. Die product.php stellt eine Klasse "Product" bereit, die in der read.php includiert wird, um die Klasse zu initialisieren

product.php
PHP:
<?php
class Product{
 
    // database connection and table name
    private $conn;
    public $table_name = "usd_eur_5min";
    
 
    // object properties
    public $time;
    public $zeit;
    public $open;
    public $high;
    public $low;
    public $close;
 
    // constructor with $db as database connection
    public function __construct($db){
        $this->conn = $db;
    }
    
    //***********************************************************//
    // read products
    function read(){
    
        // select all query
        $query = "SELECT
                    p.time, p.zeit, p.open, p.high, p.low, p.close
                FROM
                    " . $this->table_name . " p                   
                ORDER BY
                    p.time DESC";
    
        // prepare query statement
        $stmt = $this->conn->prepare($query);
    
        // execute query
        $stmt->execute();
    
        return $stmt;
    }    .....

read.php
PHP:
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
 
// include database and object files
include_once '../config/database.php';
include_once '../objects/product.php';
 
// instantiate database and product object
$database = new Database();
$db = $database->getConnection();
 
// initialize object
$product = new Product($db);
 
// query products
$stmt = $product->read();
$num = $stmt->rowCount();

// initialize table
$tabelle = $table_name;
.....

Wenn ich in der read.php mit der Variable $table_name aus der Datei product.php weiterarbeiten will, erhalte ich immer einen Fehler:
<b>Notice</b>: Undefined variable: table_name in .....

Wie kann ich denn auf die in der product.php definierte Variable $table_name in der read.php dann zugreifen?

VG
 
Weder PHP noch OOP sind meine Stärken, aber mir scheint, auf eine solche Variable kann man nur zugreifen, wenn es eine Instanz der Klasse gibt:
PHP:
    class Product{
 
        // database connection and table name
        private $conn;
        public $table_name = "usd_eur_5min";
    }
    echo $table_name; // geht nicht
    $theproduct = new Product();
    echo $theproduct->table_name; // geht
 
In der read.php in Zeile 15 wird ja eine Instanz der Klasse angelegt:

PHP:
...
// initialize object
$product = new Product($db);
....

Ich habe es auch schon mit nachfolgend

PHP:
...
$tabelle = $product->table_name;
echo $tabelle;
...
probiert und erhalte einen Syntaxerror: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
 
Zurück