Accessing a public variable from one class in PHP from another class

I've encountered an issue where I am attempting to access a public variable from one class in another class, but it returns as a blank array.

The code snippet that I'm currently working on is as follows:

Class One:

class fruits {
public $ID = array();

private function getFruitID() {
$fruitID = array('1' , '2', '3' , '4' , '5' );
return $fruitID;  
}

private function getFruitsName() {
$fruitName = array('apple' , 'orange' , 'kiwi' , 'grapes' , 'mango');
return $fruitName ;  
}

public function getstock() {    
$this->ID   = getFruitID();
/* Prints the ID list here */
$this->name = getFruitsName();
/* This function renders to the template */  

}

}

Class Two:

class TestPage{

public function displayFruits() {
require_once ('fruits.php');
$fruits = new fruits();
$data = $fruits->ID;
echo($data);
/* displays an empty array */
}     
}

Upon attempting to echo $data within the displayFruits() method of the TestPage class, it only outputs an empty array instead of the actual IDs. I'm struggling to retrieve the IDs in the TestPage class. While I could use a return statement, it would limit me to access just one variable when I have multiple variables within that function. Any assistance on this matter would be greatly appreciated.

Answer №1

you haven't initialized the array with any values..

public $ID = array();

is empty... until you invoke getFruitID

if needed, you can include it in the constructor function.

PHP constructors

function __construct( ){
   $this->getstock();
}

This means that when you create your object new Fruit();

It will populate the array during its creation process.

Answer №2

Currently, there are no items in the array.

public $ID = array();

You can add the following code to populate the array:

class TestPage{

    public function displayFruits() {
        require_once ('fruits.php');
        $fruits = new fruits();
        $fruits->getstock();
        $data = $fruits->ID;
        echo($data);

    }     
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am experiencing difficulties with the PHP login form on MAMP as it is not loading properly, displaying only a

Having trouble with php not loading when I open my browser. Here is my database info: MySQL To manage the MySQL Database, you can use phpMyAdmin. If you need to connect to the MySQL Server from your own scripts, use these connection parameters: Host ...

Troubleshooting Issues with Loading Styles and JavaScript for Wordpress Plugin in Admin Area

Can someone please help me with troubleshooting my stylesheet and scripts that are not working properly? I have included styles in the stylesheet and an alert in my script file, but for some reason they are not functioning as expected. (I have confirmed ...

What is the best way to insert a newline in a shell_exec command in PHP

I need assistance with executing a node.js file using PHP. My goal is to achieve the following in PHP: C:proj> node main.js text="This is some text. >> some more text in next line" This is my PHP script: shell_exec('node C:\pr ...

Why does PHP external API access fail when requested from a different page on the same domain?

Currently, I am experimenting with cross-site scripting using Jquery and PHP/Symfony (HttpFoundation Component), but I'm facing difficulties in obtaining the necessary data from the server. My objective is to have Jquery fetch JSON from the local dom ...

The controller in Symfony2 is unable to locate the registry service

I am working with a basic controller and need to utilize the entity manager: <?php namespace HanziGame\MainBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use HanziGame\MainBundle\E ...

How can I fetch variables from a mySQL table to utilize them in a different row within the same table?

My lack of experience in SQL/mySQL has led me here with a somewhat basic question. After unsuccessful attempts at finding answers on Google, I present to you the mySQL table that is causing me confusion. create table Contribution ( ContributionID ...

Prevent image swapping when selecting variations in Woocommerce

Can the image change be disabled when selecting a variation for a variable product? I understand that I could remove the image from the variation, but in my situation, I need to keep the variation images. Any assistance would be greatly appreciated. ...

Displaying various images within a bootstrap modal window

I'm facing an issue with my gallery. It contains small images, and when a user clicks on a thumbnail, a modal should open with the full-size image. The problem is that even though I have the full-size images stored in the "/uploads/" folder and the th ...

`Sending PHP variables to AJAX - A Step-by-Step Guide`

I've been trying to access session variable data within an ajax call, but I'm facing a roadblock. Here's my code snippet. $('#update').click(function(){ var number = $('#num').val(); ...

Why is my HTML image stored in the database not showing up in TCPDF?

Currently, my situation involves using TCPDF to retrieve content from a MySQL table row that contains HTML code like this: <p><a href="x.html"><img src="http://1/2/3/x.jpg" width="x" height="x"></a></p> The problem arises wh ...

Design a new class that features a graphical user interface, but facing challenges with the syntax

class AutoGUI: def __init__(self): import tkinter, re, uuid from tkinter.constants import * import tkinter.messagebox import socket, os, subprocess, multiprocessing, sys from getmac import get_mac_address as gma ...

Challenges encountered with a simple PHP calendar script

I created this PHP calendar template that starts from Monday instead of Sunday to suit my Italian preferences. <?php $date = strtotime("2021-10-28"); $monthNames = Array("Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", ...

Steps for developing the server side in PHP when utilizing JSON on the client side of an iPhone

Is it possible to use JSON directly to parse server-side code written in PHP? If so, could you provide some examples of how this can be done when wanting to integrate JSON on the client side? I am interested in making my server side in PHP and incorporati ...

Combine various tables when multiple IDs are stored in a single row

Within my database, I have three tables: skill, job_post, and experience. My task involves joining these tables together. Firstly, the job_post table is structured as shown here: https://i.stack.imgur.com/lySaZ.png The layout of the Skill table is as fo ...

Tips on properly implementing gzipped string decoding in PHP

I've been attempting to decipher a gzipped string from a Postman content response, like so: String for decoding: aAAAAB+LCAAAAAAABAAtyjEKgDAMQNGrhMwquPYGHVx0FIfYRqloAm11Ee+uFLfP591o5WLJFIMmNONUYZdW69HUbckhRzTY88KRxQUCAp03zgqiwCnTvLMLnsDpoRDkO4V5hl ...

Setting a background-image using jQuery in Codeigniter can be done by following these steps

Currently, I am developing a project in Codeigniter. In my jQuery file, I have included code to set the background image of the body element: $('body').css('background-image','url(<?php echo base_url("assets/images/bg2.png");?& ...

What could be causing MySQL to return a negative result when matching against columns?

Recently, I discovered the amazing benefits of using MySQL's match against, but encountered some unexpected issues. I noticed that when the joined table2 has no paired rows, MySQL's match against function returns a negative value for the join co ...

The site cache appears to be deactivated, but the source of the deactivation remains unclear. Can you help identify the issue?

On my PHP website, the <head> tag in the HTML includes: <meta http-equiv="Cache-Control" content="max-age=300"/> However, when checking the headers, it shows: Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre- ch ...

Repetitive retrieval of HTML file using Php and Ajax

I've been tackling notifications in PHP lately. Within the header file, I've included this function: $(document).ready(function() { setInterval(getNotifys, 10000); function getNotifys(){ $.ajax ({ ...

Changes made to the .htaccess file are preventing the $_GET variable from being set

For a while now, I've been utilizing '.htaccess' to modify the appearance of page URLs. Instead of: details.php?video=how+to+do+this&user=xxx I prefer it to look more like this: /details/xxx/how+to+do+this Although it's function ...