Notice: Undefined index: in class->array - php

This is the code:
class app {
public $conf = array();
public function init(){
global $conf;
$conf['theme'] = 'default';
$conf['favicon'] = 'favicon.ico';
}
public function site_title(){
return 'title';
}
}
$app = new app;
$app->init();
//output
echo $app->conf['theme'];
And I get this error:
Notice: Undefined index: theme in C:\xampp\htdocs\...\trunk\test.php on line 21
Where have I gone wrong, and is there any simpler way to get same result?

You are in the wonderful world of OOP, no longer do you have to use global!
Try this:
class app
{
public $conf = array();
// Notice this method will be called every time the object is isntantiated
// So you do not need to call init(), you can if you want, but this saves
// you a step
public function __construct()
{
// If you are accessing any member attributes, you MUST use `$this` keyword
$this->conf['theme'] = 'default';
$this->conf['favicon'] = 'favicon.ico';
}
}
$app = new app;
//output
echo $app->conf['theme'];

You are populating a separate global variable instead of the object properties. Use $this:
class app {
public $conf = array();
public function init(){
$this->conf['theme'] = 'default';
$this->conf['favicon'] = 'favicon.ico';
}
public function site_title(){
return 'title';
}
}
$app = new app;
$app->init();
//output
echo $app->conf['theme'];

Related

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();

Undefined Function Error PHP

I'm writing a class and I can't figure out why I am getting this error:
PHP Fatal error: Call to undefined method Directory::BuildDirectoryListing()
in C:\www\directory.php on line 25
It doesn't make any sense. By the error it looks like it is trying to look for a static function. Here is the code I am using:
$odata = new Directory($listing['id']);
$adata = $odata->BuildDirectoryListing();
<?php
include_once("database.php");
class Directory {
public $listing = array();
public $aacategories = array();
function __construct($_listing) {
$this->listing = $_listing;
}
public function BuildDirectoryListing() {
/* function code here */
}
}
?>
Directory is a PHP built-in class.
You need to namespace your code or change your class name:
Class:
<?php
namespace MyApp;
class Directory {
public $listing = array();
public $aacategories = array();
function __construct($_listing) {
$this->listing = $_listing;
}
public function BuildDirectoryListing() {
/* function code here */
}
}
?>
Creating the class:
<?php
$odata = new \MyApp\Directory($listing['id']);
$adata = $odata->BuildDirectoryListing();
?>
You are calling a static function in Directory::BuildDirectoryListing(), change this line
public function BuildDirectoryListing() {
for
public static function BuildDirectoryListing() {

why does this class return variable not found?

Why am i getting
Undefined variable: req
When i have declared the property at the top of my class:
<?php
namespace Craft;
class Disqus_ApiService extends BaseApplicationComponent
{
private $req = false;
public function init()
{
$d = craft()->plugins->getPlugin('disqus');
$settings = $d->getSettings();
$this->$req = new \DisqusAPI($settings['DISQUS_SECRET_KEY']);
}
public function trends()
{
return $this->req->trends;
}
}
Use
$this->req
Instead of
$this->$req
In
$this->$req = new \DisqusAPI($settings['DISQUS_SECRET_KEY']);

declaring a object inside a class, giving some weird warning

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.

How can I can get a child class's properties into the parent class's methods

I have two classes: The first class - Database - handles all the database actions, i.e., insert, update, delete. The other handles class specific actions for the user. The user class extends the database class. The User class has all of the properties in it and am trying to get the methods from the Database class to perform actions on the properties from the User class. So I'm instantiating User in test.php:
<?php
require_once("user.php");
$user = new User();
$user->auth("Scott", "rascal");
echo $user->username;
?>
<html>
<head>
<title>test</title>
</head>
<body>
</body>
</html>
and I'm getting these errors:
Notice: Undefined property: Database::$dbFields in /Users/scottmcpherson/Sites/phpsites/projectx/application/models/db.php on line 24
Warning: Invalid argument supplied for foreach() in /Users/scottmcpherson/Sites/phpsites/projectx/application/models/db.php on line 24
Notice: Undefined property: Database::$tableName in /Users/scottmcpherson/Sites/phpsites/projectx/application/models/db.php on line 83
Notice: Undefined property: Database::$id in /Users/scottmcpherson/Sites/phpsites/projectx/application/models/db.php on line 85
Notice: Undefined property: Database::$dbFields in /Users/scottmcpherson/Sites/phpsites/projectx/application/models/db.php on line 24
Warning: Invalid argument supplied for foreach() in /Users/scottmcpherson/Sites/phpsites/projectx/application/models/db.php on line 24
Here's the user class:
<?php
require_once("db.php");
class User extends Database{
public $dbFields = array('username', 'password');
public $tableName = "users";
public $id;
public $username;
public $password;
public function auth($user, $pass){
$this->username = $user;
$this->password = $pass;
}
}
?>
And here's the section of the database class that's giving me trouble:
<?php
require_once("../config/main.php");
class Database{
public $db;
public function __construct() {
$this->connect();
}
public function connect(){
try {
$this->db = new PDO("mysql:host=".DB_SERVER."; dbname=".DB_NAME, DB_USER, DB_PASS);
$this->db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
public function properties() {
$properties = array();
foreach ($this->dbFields as $field) {
if (isset($this->field) || property_exists($this, $field)) {
$properties[$field] = $this->$field;
}
}
return $properties;
}
I had everything working fine until I tried to extend the class and move the properties to the child class. How do I get past the errors and achieve this correctly?
What you did seems like it should work, just make sure to construct a User object and not a Database object directly. This is the exact point of class inheritance (having a parent run functions and reference properties that you don't have to code in every subclass).
That said, maybe try defining $dbFields as an empty array in your Database class (and your other subclass properties for that matter). Not sure if it would fix it (I usually do the late-static-binding thing), but worth a try.
In your parent class declare variables as static and if they exist in the child class, they will be used in the parent class. Check out Late Static Binding (LSB)
You try to access dbFields in your Database class but it is declared in your User class.
IMO, you should declare the dbFields in your Database class & you can set this property in the User constructor.
Hey I just had the same problem but I could figure this out using late static binding here is my example some of the codes are extra from my own just focus on the show_fields() function
<?php
class x {
protected static $table_name;
public static $fields = array();
public function __construct() {
self::set_table_name();
}
public function called_class() {
return __CLASS__;
}
public function set_table_name() {
self::$table_name = static::called_class();
}
public function test() {
echo self::$table_name;
}
public function show_fields() {
echo "<pre>";
print_r(static::$fields);
echo "</pre>";
echo "<br />";
foreach (static::$fields as $key => $value) {
if(property_exists(static::$table_name, $value)) {
echo static::$$value . "<br />";
}
}
}
}
class y extends x {
public static $fields = array('id','title');
public static $id = 'new id';
public static $title = 'new title';
public function called_class() {
return __CLASS__;
}
}
$xx = new x();
$yy = new y();
$yy->test();
$yy->show_fields();
?>

Categories