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?
Related
I would like overwrite array element returned as reference. I can do it like this:
$tmp = $this->event_users_details;
$tmp = &$tmp->firstValue("surcharge");
$tmp += $debt_amount;
I would do it in one line like:
$this->event_users_details->firstValue("surcharge") += $debt_amount;
but I get Can't use method return value in write context
Where $this->event_users_details is a object injected in constructor.
My function look like:
public function & firstValue(string $property) {
return $this->first()->{$property};
}
public function first() : EventUserDetails {
return reset($this->users);
}
and users is a private array.
You can't do it without temporary variable stores "surcharge" value.
From documentation:
To return a reference from a function, use the reference operator & in both the function declaration and when assigning the returned value to a variable:
<?php
function &returns_reference()
{
return $someref;
}
$newref =& returns_reference();
?>
I checked it with this code:
class Item
{
public $foo = 0;
}
class Container
{
private $arr = [];
public function __construct()
{
$this->arr = [new Item()];
}
public function &firstValue($propNme)
{
return $this->first()->{$propNme};
}
private function first()
{
return reset($this->arr);
}
}
$container = new Container();
var_dump($value = &$container->firstValue('foo')); // 0
$value += 1;
var_dump($container->firstValue('foo')); // 1
I have 3 separate files, item.php, proposal.php and output.php - this is supposed to be a cart like application, the idea is to for the user to select an item and the item in to the Proposal class... however I am running in to the following error:
Fatal error: Uncaught Error: Cannot use object of type __PHP_Incomplete_Class as array in C:\xampp\htdocs\proposal.php:12 Stack trace: #0 C:\xampp\htdocs\output.php(9): Proposal->addItem(Object(Item)) #1 {main} thrown in C:\xampp\htdocs\proposal.php on line 12
I've searched around SO & Google, and tried various things including placing session_start() before the includes for item.php and proposal.php, however that did not solve the issue, the error just changed to:
Cannot use object of type Proposal as array
Any ideas? Running PHP 7.0.9
item.php
<?php
class Item {
protected $id;
protected $name;
protected $manufacturer;
protected $model;
protected $qty;
protected $serial;
public function __construct($id,$name,$manufacturer,$model,$qty,$serial) {
$this->id = $id;
$this->name = $name;
$this->manufacturer = $manufacturer;
$this->model = $model;
$this->qty = $qty;
$this->serial = $serial;
}
public function getId() {
return $this->id;
}
public function getName() {
return $this->name;
}
public function getManufacturer() {
return $this->manufacturer;
}
public function getModel() {
return $this->model;
}
public function getQty() {
return $this->qty;
}
public function getSerial() {
return $this->serial;
}
}
proposal.php
class Proposal {
protected $items = array();
public function __construct() {
$this->items = isset($_SESSION['proposal']) ? $_SESSION['proposal'] : array();
}
public function addItem(Item $item) {
$id = $item->getId();
// the following line is line 12 of proposal.php
if(isset($this->items[$id])) {
$this->items[$id]['qty'] = $this->items[$id]['qty'] + $item->getQty();
}
else {
$this->items[$id] = $item;
}
}
}
output.php
session_start();
include('item.php');
include('proposal.php');
$item = new Item($_GET['id'],$_GET['name'],$_GET['manufacturer'],$_GET['model'],$_GET['qty'],$_GET['serial']);
$proposal = new Proposal();
$proposal->addItem($item);
$_SESSION['proposal'] = $proposal;
// view output in array/object format if session variable set
if(isset($_SESSION['proposal'])) { print '<pre>' . print_r($_SESSION['proposal'],1) . '</pre>'; }
EDIT: I believe this issue may be session related because the error does not appear until the 2nd run.
Output on first run is:
Proposal Object
(
[items:protected] => Array
(
[25] => Item Object
(
[id:protected] => 25
[name:protected] => Computer
[manufacturer:protected] => Dell
[model:protected] => Alienware
[qty:protected] => 11
[serial:protected] => 12345678
)
)
)
session_start();
include('item.php');
include('proposal.php');
Your session is initialized before classes have been declared.
This is leading to __PHP_Incomplete_Class.
Problem with "Cannot use object of type Proposal as array":
public function __construct() {
$this->items = isset($_SESSION['proposal']) ? $_SESSION['proposal'] : array();
}
If your session contains key proposal, you are using it as storage variable, but this is initialized as instance of Proposal in output.php:
$proposal = new Proposal();
$proposal->addItem($item);
$_SESSION['proposal'] = $proposal;
One way to avoid this is to create a session singleton of Proposal:
class Proposal {
protected function __construct() {}
public static function getInstance()
{
if (!isset($_SESSION['proposal'])) {
$_SESSION['proposal'] = new Proposal;
}
return $_SESSION['proposal'];
}
}
I'm trying to persist a domain model to a DB without using an ORM just for fun.
It's pretty easy to persist properties, but I'm having hard time persisting a collection.
Let's say I have the following two objects.
class aModel
{
private $items = [];
public function __construct($id, $name, array $items = [])
{
$this->id = $id;
$this->name = $name;
$this->items = $items;
}
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
public function addItem(Item $item)
{
$this->items[] = $item;
}
}
class aDBRepository
{
public function persist(aModel $aModel)
{
$attributes = [
'id' => $aModel->getId(),
'name' => $aModel->getName()
];
$this->table->insert($attributes);
}
}
// Code
$aModel = new aModel("test id", "a name");
$aModel->addItem(new Item("id", "name"));
When I create a new aModel and add a new item to it, how do I detect 'unsaved' items and persist them?
I can only think of adding isSaved method in the Item class and loop through $items variable in aModel.
Without using reflection, what's the best way?
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);
}
}
I am trying to declare an object of type Spell in my class Game like this:
<?php
require 'Spell.php';
class Game
{
public $Name;
public $Spell;
function Game()
{
$Name[0] = 0;
$Spell = new Spell;
}
This is returning this warning:
"Warning: Creating default object from empty value in"
and I'm not sure why.
Try the following:
class Game
{
public $Name = array();
public $Spell;
function Game()
{
$this->Name[0] = 0;
$this->Spell = new Spell();
}
}
You should use
function Game()
{
$this->Name = [ 0 ];
$this->Spell = new Spell();
}
Check this question for more details on the error.