Skip to content
Advertisement

PHP, how do I pass variables between methods?

I’m trying to pass a variable from one method to another.

I’m fetching dates from an events table in order to build a dynamic query in another method.

class Player extends Database {
    private $start_date;
    private $end_date;
    private $sumCase;

protected function getEvents() {
        $sql = "SELECT * FROM `events`";
        $stmt = $this->connect()->prepare($sql);
        $stmt->execute();
        $results = $stmt->fetchAll();

        $event_arr = array();
        foreach($results as $result) {
            $event_name = $result['event_name'];
            $this->start_date = $result['start_date'];
            $this->end_date = $result['end_date'];

            $this->sumCase[] = "SUM(CASE WHEN date BETWEEN $this->start_date AND $this->end_date THEN 1 ELSE 0 END) '$event_name'";
            $dateBetween[] = "date BETWEEN $this->start_date AND $this->end_date";
            array_push($event_arr, array(
                "name" => $result['event_name'],
                "start" => $result['start_date'],
                "end" => $result['end_date'],
            ));
        }
        return print_r($this->sumCase);
    }

this returns my sumCase array without problems, I’m now trying to access this sumCase array in another method in order to build the query:

protected function getPlayerEvents() {
        $sql = "SELECT count(chalID) as total, ";
        $sql .=' '.implode(', ', $this->sumCase); 
        $sql .="from (SELECT * FROM times where ("; //ignore this
        $sql .="date BETWEEN 159310659 AND 1593538594  OR date BETWEEN 1693538594 AND 1793538594"; //ignore this
        $sql .=") AND plaID = 1 group by chalID) A"; //ignore this

        $stmt = $this->connect()->prepare($sql);
        $stmt->execute();
        $results = $stmt->fetchAll();
        echo $this->sumCase; //returns null, how do I pass variables between methods?
    }

when I echo my sumCase array within this method, it returns null. How do I access the value of the sumCase array from the getEvents method?

Advertisement

Answer

It returns null if function getEvents wasnt called first or it was called not to same instance of object.

<?php

use directory_with_classesPlayer;

$player = new Player();
$player->getEvents();
$player->getPlayerEvents();

?>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement