declaring a object inside a class, giving some weird warning - php

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.

Related

Why isn't the array I return in my __construct class available in the following function?

I've written a class which in the construct accesses the db and gets a list of names. These names go into an associative array e.g. ('name' => 'id').
i.e. the point is to pass in the name to get back an ID:
$id = names::nameToId('some name');
print $id;
// prints int
The problem is when I try and return the array from the construct I get an error:
Notice: Undefined variable: nameArray in (etc)
Here is the code so far:
class nameToId {
public $nameArray;
private $mysqli;
public function __construct($mysqli) {
...
while($row = mysqli_fetch_assoc($res)) {
$nameArray[$row['name']] = $row['id'];
}
return $nameArray;
}
static public function nameToId($name) {
$nameId = $nameArray[$name];
return $nameId;
}
}
$namesToId = new nameToId($mysqli);
$nameId = $namesToId::nameToId('some name');
echo $nameId;
Why doesn't $nameArray get passed to nameToId()? I'm new to classes, and I thought by declaring $nameArray as public when I first create the class that it would make it available. I have also tried to make it global even though I know that is not good form but even still it didn't work.
Because you cannot return anything from a constructor. Any return value is being ignored and just goes into the aether. $nameArray is a local variable and is not shared in any other scope, i.e. you can't access it in nameToId. Further, since nameToId is static, it won't have access to data from any non-static methods like __construct to begin with.
You probably want something like this:
class nameToId {
public $nameArray;
private $mysqli;
public function __construct($mysqli) {
...
while ($row = mysqli_fetch_assoc($res)) {
$this->nameArray[$row['name']] = $row['id'];
}
}
public function nameToId($name) {
return $this->nameArray[$name];
}
}
$namesToId = new nameToId($mysqli);
echo $namesToId->nameToId('some name');
Fix your code:
class nameToId {
public static $nameArray;
private $mysqli;
public function __construct($mysqli) {
$this->mysqli = $mysqli;
$sql = 'SELECT id, name FROM teams';
$res = mysqli_query($this->mysqli,$sql);
while($row = mysqli_fetch_assoc($res)) {
self::$nameArray[$row['name']] = $row['id'];
}
}
static public function nameToId($name) {
$nameId = self::$nameArray[$name];
return $nameId;
}
}
$namesToId = new nameToId($mysqli);
$nameId = $namesToId::nameToId('some name');
echo $nameId;

Send back to Ajax with OOP

New to OOP, figured I'd practice a bit by sending back data from PHP via ajax. What am I doing wrong here? It works if I change the code to procedural. Here's the OOP:
if (isset($_POST['fruity'])) {
$start_fruity = new Fruity_draft();
$start_fruity->send_json();
}
class Fruity_draft {
public $banned = $_POST['banned'];
public $players = $_POST['players'];
public $random_civs = $_POST['random_civs'];
public $array_list = [];
public $send_json['banned'] = $banned;
function __construct($send_json) {
$this->send_json = $send_json;
}
function send_json() {
echo json_encode($this->send_json);
}
}
First of all, you forgot about passing a parameter to the constructor, it expects an array.
function __construct($send_json) {
In your call, you don't send anything
$start_fruity = new Fruity_draft();
This throws a warning, Warning: Missing Argument 1
and a notice, Notice: Undefined variable: send_json
Second, you should move the initialization of the class variables in the constructor.
class Fruity_draft {
public $banned;
public $players;
public $random_civs;
public $array_list;
public $send_json;
function __construct($send_json) {
$this->banned = 'banned';
$this->players = 'players';
$this->random_civs = 'random_civs';
$this->send_json = $send_json;
$this->send_json['banned'] = $this->banned;
}
...
}
That's not really OOP :). You should return something from the class, not echo.
Also, you should send data from other function to the class.. in the constructor or with a method set_post_data() or something...
Simple:
if (isset($_POST['fruity'])) {
$start_fruity = new Fruity_draft($_POST);
echo $start_fruity->get_json_response();
}
class Fruity_draft {
private $postData;
function __construct($postData) {
$this->postData = $postData;
}
function get_json_response() {
return json_encode($this->postData['banned']);
}
}

How can I create dynamically objects based on array values in php?

I'ld like to dynamically create as many object as present in my $instance array (e.g. domain1_com and domain2_com) and give them the name of array value (e.g. domain1_com and domain2_com) so I can access it through these names (e.g. domain1_com->example()).
Is it possible? I tried something like this but obviously doesn't work.
class myClass
{
public static function getInstances()
{
// I connect to the database and execute the query
$sql = "SELECT * FROM my_table";
$core = Core::getInstance();
$stmt = $core->dbh->prepare($sql);
if ($stmt->execute()) {
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
// Read values in my array
foreach ($results as $instance) {
$obj = $instance["domain"]);
// return 2 values: domain1_com and domain2_com
$obj = new myClass();
}
}
public function example()
{
echo "This is an instance";
}
}
myClass::getInstances();
$domain1_com->example();
$domain2_com->example();
You can use variable variables.
$name = "foo";
$$name = new bar();
is the same as
$foo = new bar();
You cannot access the variables created inside getInstances outside of that method. They are local, not global.
Try this code:
class myClass
{
public static function getInstances()
{
$results = array('domain1_com', 'domain2_com');
foreach ($results as $instance) {
$$instance = new myClass();
// This is equivalent to "$domainX_com = new myClass();".
// Writing that code here would define a _local_ variable named 'domainX_com'.
// This being a method inside a class any variables you define in here are _local_,
// so you can't access them' _outside_ of this method ('getInstances')
}
// this will work, we are inside 'getInstances'
$domain1_com->example();
$domain2_com->example();
}
public function example()
{
echo "This is an instance";
}
}
myClass::getInstances();
// this won't work. $domainX_com are not accessible here. they only exist _inside_ 'getInstances'
// It's basic OOP.
// so this code will crash
$domain1_com->example();
$domain2_com->example();
It will produce this output:
This is an instance
This is an instance
E_NOTICE : type 8 -- Undefined variable: domain1_com -- at line 32
E_ERROR : type 1 -- Call to a member function example() on a non-object -- at line 32
You need a way to access those variables. I'd use this:
class myClass
{
private static $instances = array();
public static function getInstances()
{
$results = array('domain1_com', 'domain2_com');
foreach ($results as $instanceName) {
self::$instances[$instanceName] = new myClass();
}
}
public static function getInstance($instanceName) {
return self::$instances[$instanceName];
}
public function example()
{
echo "This is an instance";
}
}
myClass::getInstances();
// this will work
myClass::getInstance('domain1_com')->example();
myClass::getInstance('domain2_com')->example();

PHP Notice: undefined variable, but they are already defined

In my PHP script I get the error variable $command_in_hostfile undefined.
There are two functions in my class.
In the first function I return an array ($command_in_hostfile) to use it in another function.
However, I get the error "variable undefined" and I donĀ“t understand why. Can anyone help me rectify this error?
Code:
include_once('service_function.php');
if(isset($_POST['edit_cfg_file']))
{
$Host = new Host;
$Host->write_hostfile();
}
public $command_in_hostfile = array();
class Host
{
public $command_in_hostfile = array();
function read_services()
{
...
$command_in_hostfile[0] = array_merge($command_in_hostfile[0]);
$command_in_hostfile[1] = array_merge($command_in_hostfile[1]);
return($command_in_hostfile);
}
function write_hostfile()
{
foreach($command_in_hostfile[0] as $key=>$value)
{
$checkcommand[$key] = "check_command ".$value."!".$value2_converted."\n";
}
}
}
?>
try using $this->
$command_in_hostfile = array();
class Host
{
public $command_in_hostfile = array();
function read_services()
{
...
$this->command_in_hostfile[0] = array_merge($command_in_hostfile[0]);
$this->command_in_hostfile[1] = array_merge($command_in_hostfile[1]);
return($this->command_in_hostfile);
}
function write_hostfile()
{
foreach($this->command_in_hostfile as $key=>$value)
{
$checkcommand[$key] = "check_command ".$value."!".$value2_converted."\n";
}
}
}

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