PHP call public variable in another class - php

I am trying to call a public variable used in a class in another class. I am able to call the variable but it returns a blank array.
Code that I am working on,
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 */
}
}
When I echo $data inside displayFruits() on TestPage, it prints a blank array and not the actual ids. I am stuck with getting the ids on TestPage class. I could use a return, but that way I would end with just one variable, and I have multiple variables inside that function. Any help would be much appreciated.

you are not contructing the array with anything ..
public $ID = array();
is blank... until you call getFruitID
you can add it into the constructor if you need.
constructors PHP
function __construct( ){
$this->getstock();
}
This means when you create your object new Fruit();
It will assign the array in its creation.

At the moment it is empty.
public $ID = array();
Add below to populate array
class TestPage{
public function displayFruits() {
require_once ('fruits.php');
$fruits = new fruits();
$fruits->getstock();
$data = $fruits->ID;
echo($data);
}
}

Related

Extended class gets only initial value of parent's variable

class MyAppClass {
protected $_config = array();
protected $_template = '';
public function init( ){
require_once('core_config.php'); // Inside is $_SC_config with an array of values
$this->_config = $_SC_config;
$this->_template = new template;
echo $this->_template->echo_base();
}
}
class template extends MyAppClass{
public function echo_base() {
var_dump($this->_config); // returns empty array
}
}
$myApp = new MyAppClass;
$myApp->init();
What's wrong with code above so
var_dump($this->_config)
in template class returns empty array after init function?
Thanks in advance.
I think you don't get object programming yet. In MyAppClass::init method you create new object of template class which extends your MyAppClass class. I have no idea what do you want to acheve but I will show you snippet which works.
<?php
class MyAppClass {
protected $_config = array();
protected $_template = '';
protected function init( ){
//require_once('core_config.php'); // Inside is $_SC_config with an array of values
$this->_config = 'foo';
}
}
class template extends MyAppClass{
public function __construct(){
$this->init();
}
public function echo_base() {
var_dump($this->_config); // returns empty array
}
}
$myApp = new template;
$myApp->echo_base();

Clarify a line/s --> setting sql data into object variables

This is my first question here and I will try to clarify it as much as possible.
I am a begginer and I am going through lynda - beyond PHP MySQL lessons when I got to this part.
Code is working just fine, I just need better explanation for myself to the line that is commented in a code.
require_once('database.php');
class User {
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
public static function find_all() {
return self::find_by_sql("SELECT * FROM users");
}
/////
public static function find_by_sql($sql="") {
global $database;
$result_set = $database->query($sql);
$user_array = array();
while ($row = $database->fetch_array($result_set)) {
$user_array[] = self::instantiate($row);
}
return $user_array;
}
And finaly lines that i almost understand :)
private static function instantiate($row) {
$user = new self;
foreach($row as $attribute=>$value){
if($user->has_attribute($attribute)) {
$user->$attribute = $value; /// THIS LINE BUGS ME
}
}
return $user;
}
private function has_attribute($attribute) {
$user_vars = get_object_vars($this);
return array_key_exists($attribute, $user_vars);
}
}
So I think I don't understand array_key_exists which returns TRUE or FALSE, in my case its true, but then line $users->$attributes =$value ; makes no sense for me,
So, I check if keys from fetch array MATCH variable names from object,
if($user->has_attribute($attribute)) { //and then this is true,perform nxt line
$user->$attribute = $value; // i got match of attribute above,how does it put values in $user_vars???
I know it says something like " if user has same attribute as key from that fetch array then put into that same attribute value of that attribute $value but i just dont see how it is done when i never returned object variables
Thank you for your time !
edit:
class variables names are equal to names of column_names from database
The User class has public attributes $id, $username, $password, etc. That means that you can assign values to the attributes in the following form:
$u = new User;
$u->id = 123;
$u->username = 'username';
and using dynamic property names:
$prop = 'id';
$u->$prop = 123;
$prop = 'username';
$u->$prop = 'username';
This is just the thing that happens in the lines that you don't understand:
if ($user->has_attribute($attribute)) {
$user->$attribute = $value;
The has_attribute method fetches all attributes of the $user object with get_object_vars function. The latter fetches the object properties as an array:
$user_vars = get_object_vars($this);
/* i.e.
$user_vars = array (
'id' => ...,
'username' => ...,
...
);
*/
Then the has_attribute method checks if the given $attribute key exists in the array of properties:
return array_key_exists($attribute, $user_vars);
If it exists (true), the $attribute property is assigned to $value.

Array reference in a class error in php

I have this class which populates and prints an array
<?php
class testArray
{
private $myArr;
public function __construct() {
$myArr = array();
}
public static function PopulateArr() {
$testA = new testArray();
$testA->populateProtectedArr();
return $testA;
}
protected function populateProtectedArr()
{
$this->myArr[0] = 'red';
$this->myArr[1] = 'green';
$this->myArr[2] = 'yellow';
print_r ($this->myArr);
}
public function printArr() {
echo "<br> 2nd Array";
print_r ($this->myArr);
}
}
?>
I instantiate this class from another file and try to print the array in different function.
<?php
require_once "testClass.php";
$u = new testArray();
$u->PopulateArr();
$u->printArr();
?>
I am not able to print the array in the printArr() function. I want to get reference to the array that I had set the values in .
You just missed one thing, you have to assign result of $u->PopulateArr(); to $u again, otherwise you will not get the object you created from that method call, so:
$u = new testArray();
$u = $u->PopulateArr(); // this will work
$u->printArr();
This also can be done like this:
$u = testArray::PopulateArr();
$u->printArr();
It seems that your $u object never populates the private array.
Instead you create a new object $testA and populate its array.
This might help you understanding the way
class testArray
{
private $myArr;
public function __construct() {
$this->myArr = array();
}
public static function PopulateArr() {
$testA = new testArray();
$testA->populateProtectedArr();
return $testA;
}
protected function populateProtectedArr()
{
$this->myArr[0] = 'red';
$this->myArr[1] = 'green';
$this->myArr[2] = 'yellow';
return $this->myArr;
}
public function printArr() {
echo "<br> 2nd Array";
return $this->PopulateArr();
}
}
another.php
require_once "testClass.php";
$u = new testArray();
print_r($u->PopulateArr());
print_r($u->printArr());
Here we are accessing the values of protected function PopulateArr instead of printing within function I just replaced it with return and print it over another file and within printArr function just call the PopulateArr function and that's it

php putting an array from _construct into function

II'm using an API and was wondering why I am having trouble getting an array to cross into a function. The following works fine but how can I make it work for an array.
public function __construct()
{
parent::__construct(); // Init parent constructor
$this->dbConnect();
$this->test();
}
public function test()
{
$this->category = "bracelets";
}
private function piece()
{
// Pass an array into this function here and then use depending on array key
$cat = $this->category;
}
So instead of a constant $this->category="bracelets. I would like this to be an array. e.g.
public function test()
{
$array = [
"foo" => "bar",
"bar" => "foo",
];
$this->category = $array;
}
Ok, this has been resolved. It was due to a minor error elsewhere. For a moment I believed there was an issue with arrays in a restful API.
I hope this is useful to any others who wish to pass one function results to another in an api class.
Looking at you code, it seems you want the category property to be an array of all categories, read from the database..?
I did spot some bugs in your code:
You have variable name mixups on $cat_array vs. $cat_arr
You select cat column from DB but try read category
I have made slight changes in your test() method to fix it:
public function __construct()
{
parent::__construct(); // Init parent constructor
$this->dbConnect();
$this->test();
}
// Array with name of all categories, indexed by category id
private $category;
public function test()
{
$query = "SELECT c.id, c.cat FROM category c order by c.id asc";
$cat = $this->mysqli->query($query)
or die ($this->mysqli->error . __LINE__);
if ($cat->num_rows > 0) {
$cat_array = array();
while ($crow = $cat->fetch_assoc()) {
$id = $crow['id'];
$cat_array[$id] = $crow['cat'];
//$cat_array[$crow['id']]=$crow['category'];
}
$this->category = $cat_array;
//$this->response($this->json($result), 200); // send details
}
}
private function piece()
{
// Pass an array into this function here and then use depending on array key
$cat = $this->category;
// Check if it is working as expected
print_r($cat);
}

How to call and view an array in a function

I'm new to PHP and Kohana.
I would like to know how to call an array in a function.
I'm having the variable $productlist and I would like to add more elements into it with a function.
public $productlist = array();
public function action_index()
{
$product = new Product("Laptop","HP4897");
$product2 = new Product("TV","Samsung 8773");
$productlist[] = product;
$productlist[] = product2;
$this->add_product_to_array("Ebook","Everything you want to know");
$this->show_productlist();
}
public function add_product_to_array($product_name, $product_description)
{
$newproduct = new Product($product_name, $product_description);
array_push($productlist,$newproduct);
}
public function show_productlist(){
foreach($productlist as $key => $value)
{
print_r($value->get_product_name().'</br>');
}
}
and this is the exception i'm getting:
*ErrorException [ Warning ]: array_push() expects parameter 1 to be array, null given*
if I'm adding foreach($this->productlist as $key => $value), it tells me it can't find productlist.
Product.php
class Product {
private $_product_name;
private $_product_description;
function __construct($name,$description)
{
$this->_product_name = $name;
$this->_product_description = $description;
}
public function get_product_name()
{
return $this->_product_name;
}
//etc
PHP Classes and Objects - The Basics
Inside the class when you access the $productlist array you need to use $this->productlist. You seem to have known this in the Product class. What happened?

Categories