Hello i'm having trouble with this class when it comes to multidimensional arrays and setting them and i cannot understand why is behaving like this...
Anyone who can help me fix it?
Few Usage Examples:
echo $config->session->gcDivisor;
echo $config['session']['gcDivisor'];
$config['logged'] = '1';
$config->logged = '1';
$config['user']['logged'] = '1';
$config->user->logged = '1';
Errors for each of the lines
Notice: Trying to get property of non-object in /home/biroexpert/subdomains/prod/index.php on line 33
200
Notice: Undefined index: user in /home/biroexpert/subdomains/prod/Library/Twelve/Config/Config.php on line 67
Notice: Indirect modification of overloaded element of Twelve\Config\Config has no effect in /home/biroexpert/subdomains/prod/index.php on line 37
Notice: Undefined index: user in /home//subdomains/prod/Library/Twelve/Config/Config.php on line 87
Notice: Indirect modification of overloaded property Twelve\Config\Config::$user has no effect in /home//subdomains/prod/index.php on line 38
Strict Standards: Creating default object from empty value in /home//subdomains/prod/index.php on line 38
Code
<?php
namespace Twelve\Config;
use \ArrayObject;
use \Twelve\SingletonPattern\LazySingleton;
use \Twelve\SingletonPattern\Interfaces\ILazySingleton;
/**
* Singleton With Configuration Info
*/
class Config extends ArrayObject implements ILazySingleton
{
/**
* Stores FileName
* #var Config
*/
protected static $_configFile = '';
/**
* Config Settings Array
* #var Config
*/
protected $_settings = array();
public static function getInstance(){
return LazySingleton::getInstance(__CLASS__);
}
/**
* Set the Config File Path
*/
public static function setFile($filePath)
{
static::$_configFile = $filePath;
}
public function __construct()
{
LazySingleton::validate(__CLASS__);
$values = include(static::$_configFile);
if(is_array($values))
{
// Allow accessing properties as either array keys or object properties:
$this->_settings = new ArrayObject($values, ArrayObject::ARRAY_AS_PROPS);
}
}
// some debug method
public function dumpArray()
{
echo "<pre>";
print_r($this->_settings);
}
public function getIterator()
{
return $this->_settings->getIterator();
}
public function offsetExists($index)
{
return $this->_settings->offsetExists($index);
}
public function offsetGet($index)
{
return $this->_settings->offsetGet($index);
}
public function offsetSet($key, $value)
{
return $this->_settings->offsetSet($key, $value);
}
public function offsetUnset($index)
{
return $this->_settings->offsetUnset($index);
}
public function count()
{
return $this->_settings->count();
}
/**
* Prevent Cloning
*/
public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
// No Cloning Allowed
}
}
Related
I'll try to use fetch_object('Classname') to test this method.
The Class Inserent in Inserent.php:
namespace classes\model;
class Inserent{
private $nummer;
private $nickname;
private $email;
public function __construct ($nummer, $nickname, $email){
$this->nummer = $nummer;
$this->nickname = $nickname;
$this->email = $email;
}
public function getNummer(){
return $this->nummer;
}
public function setNummer($nummer){
$this->nummer = $nummer;
}
...
}
The use is in a Mapper-Class InserentDAO.php:
namespace classes\mapper;
use classes\model\Inserent;
class InserentDAO{
private $dbConnect;
public function __construct (){
$this->dbConnect = MySQLDatabase::getInstance();
}
public function readAll(){
$sql = "SELECT inserentennummer, nickname, email FROM inserent";
$inserent = null;
$inserentList = array();
if ($result = $this->dbConnect->query($sql)) {
while ($inserent = $result->fetch_object('classes\model\Inserent')) {
$inserentList[] = $inserent;
}
$result->close();
}
return $inserentList;
}
...
}
I get errors and my Objects are empty:
Warning: Missing argument 1 for classes\model\Inserent::__construct()
in D:\xampp\htdocs\workspace\secondStep\classes\model\Inserent.php on
line 10
Warning: Missing argument 2 for classes\model\Inserent::__construct()
in D:\xampp\htdocs\workspace\secondStep\classes\model\Inserent.php on
line 10
Warning: Missing argument 3 for classes\model\Inserent::__construct()
in D:\xampp\htdocs\workspace\secondStep\classes\model\Inserent.php on
line 10
Notice: Undefined variable: nummer in
D:\xampp\htdocs\workspace\secondStep\classes\model\Inserent.php on
line 11
Notice: Undefined variable: nickname in
D:\xampp\htdocs\workspace\secondStep\classes\model\Inserent.php on
line 12
Notice: Undefined variable: email in
D:\xampp\htdocs\workspace\secondStep\classes\model\Inserent.php on
line 13
But if I change the code, in the Mapper, it will works.
part of the code InserentDAO.php instead:
while ($obj = $result->fetch_object()) {
$inserent = new Inserent($obj->inserentennummer, $obj->nickname, $obj->email);
$inserentList[] = $inserent;
}
I believe fetch_object invokes an empty constructor and then sets the properties according to result columns it fetched. There is a comment on the manual confirming that.
So this is what fetch_object("classes\model\Inserent") is doing:
$object = new classes\model\Inserent();
$object->inserentennummer = $result['inserentennumer'];
$object->nickname = $result['nickname'];
$object->email = $result['email'];
return $object;
This is why it's complaining about missing parameters and undefined variables (they're private).
The obvious solution is to refactor your class to provide an empty constructor and public properties:
namespace classes\model;
class Inserent{
public $nummer;
public $nickname;
public $email;
public function __construct ($nummer = 0, $nickname = "", $email = ""){
//...
An alternative to making the properties public would be to use the __set magic method, but you'd still have to provide a zero-parameter constructor.
Thank you for your answer!!
I had to change the constructor in my Class Inserenten.php in the way that you explain. Also I had to change the property name from "$nummer" to "$inserentennummer", because the database table property has this name. Also I had to add querys to the constructor.
The method __set() was no help.
class Inserent{
private $inserentennummer;
private $nickname;
private $email;
public function __construct ($inserentennummer = 0, $nickname = "", $email = ""){
if(!$this->inserentennummer){
$this->inserentennummer = $inserentennummer;
}
if(!$this->nickname){
$this->nickname = $nickname;
}
if(!$this->email){
$this->email = $email;
}
}
And then it's working :-)
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'];
}
}
The url to JSON structure
http://api.giphy.com/v1/gifs/search?q=funny+cat&offset=100&limit=1&api_key=dc6zaTOxFJmzC
Now I'm trying to parse this Json data to my objects:
this is my class:
<?php
class MappedEntity{
private $id;
private $mp4Url;
public function setId($id){
$this->id=$id;
}
public function setMp4Url($mp4Url){
$this->mp4Url=$mp4Url;
}
public function getId(){
return $id;
}
public function getMp4Url(){
return $mp4Url;
}
function __contruct($jsonData){
foreach($jsonData as $key => $val){
if(property_exists(__CLASS__,$key)){
$this->$key = $val;
}
}
}
}
?>
the code thats calling the class:
<?php
require_once 'mappedEntity.php';
$keyword = $_POST["keyword"];
$url="http://api.giphy.com/v1/gifs/search?q=".$keyword."&offset=100&limit=1&api_key=dc6zaTOxFJmzC";
$json = file_get_contents($url);
$file = json_decode($json);
$entity = new MappedEntity($file);
echo $entity->getId();
?>
Im getting
Notice:
Undefined variable: id in C:...\MappedEntity.php on line 14
which is following ine
13 public function getId(){
14 return $id;
15 }
OK, I changed the getter methods, and constructor , now the error goes
Notice: Undefined variable: id in C:\....\MappedEntity.php on line 14
Fatal error: Cannot access empty property in C:...\MappedEntity.php on line 14
I assume , my mapping method inside of constructor is not working fine?
You're missing the $this on both getID and getMp4URL functions, they should read:
public function getId(){
return $this->id;
}
and
public function getMp4Url(){
return $this->mp4Url;
}
these are some example code I have written
<?php
/**************** code block 1 *****************/
class Database1
{
public $rows;
public function __construct()
{
}
public function assingrow()
{
$this->rows=5;
}
}
$database1 = new Database1();
$database1->assingrow();
echo $database1->rows;
//no error
/**************** code block 2 *****************/
class Database2
{
protected $rows;//
public function __construct()
{
}
public function assingrow()
{
$this->rows=5;
}
}
$database2 = new Database2();
$database2->assingrow();
echo $database2->rows;
//error message
//Fatal error: Cannot access protected property Database2::$rows in E:\xampp\htdocs\pdo\4.php on line 46
/**************** code block 3 *****************/
class Database3
{
public $rows;
public function __construct()
{
}
protected function assingrow()////
{
$this->rows=5;
}
}
$database3 = new Database3();
$database3->assingrow();
echo $database3->rows;
//error message
//Fatal error: Call to protected method Database3::assingrow() from context '' in E:\xampp\htdocs\pdo\4.php on line 68
/**************** code block 4 *****************/
class Database4
{
public $rows;
protected function __construct()
{
}
public function assingrow()
{
$this->rows=5;
}
}
$database4 = new Database4();
$database4->assingrow();
echo $database4->rows;
//error message
//Fatal error: Call to protected Database4::__construct() from invalid context in E:\xampp\htdocs\pdo\4.php on line 91
can somebody explain why these
why cant assign value to protected property in code block 2
why cant assign value to public property using protected method in code block 3
why construct cant be protected in code block 4
This is the purpose of Visibility.
In Block 2 your property is protected. This means it can only be accessed the class itself (Database2) and by inherited classes. The error occurs when you try to echo the variable from the outside.
The same goes for the method in Block 3.
The Constuctor can be protected or even private. But you cannot call it from the outside anymore. But something like this is possible:
class Foo
{
private function __construct()
{
}
public static function create()
{
return new self();
}
}
$foo = Foo::create();
this is my first question
I Have following class
class ProDetection {
public function ProDetection ( ) { }
public function detect($word) {
............
}
public function getScore() {
return $score;
}
}
class SaveDetection {
public function SaveDetection($words) {
$proDetection = new ProDetection();
for($i=0;$i<sizeof($words);$i++) {
$proDetection->detect($words[$i]);
}
}
public function getScore() {
return $this->proDetection->getScore();\\line 22
}
}
in other PHP file, i'm try to calling SaveDetection to getScore();
$konten = "xxxx xxxx xxx";
$save = new SaveDetection($konten);
print_r( $save->getScore() );
But i got an error message
Notice: Undefined property: SaveDetection::$proDetection in C:\xampp\htdocs\inovasi\SaveDetection.php on line 22
Fatal error: Call to a member function getScore() on a non-object in C:\xampp\htdocs\inovasi\SaveDetection.php on line 22
Please need your help
You never declare the the $proDetection member variable. Basically in your SaveDetection constructor you are declaring $proDetection as a local variable
class SaveDetection {
public function SaveDetection($words) {
$this->proDetection = new ProDetection();
for($i=0;$i<sizeof($words);$i++) {
$this->proDetection->detect($words[$i]);
}
}
public function getScore() {
return $this->proDetection->getScore();\\line 22
}
private $proDetection;
}
EDIT:
PS. You should really use PHP's __construct() syntax instead of the old style of constructors. See here.
class SaveDetection {
public function __construct($words) {
$this->proDetection = new ProDetection();
for($i=0;$i<sizeof($words);$i++) {
$this->proDetection->detect($words[$i]);
}
}
Try this. Declare your variables as private (Coz if your code grows, it is hard to find what all the object or variables are used in the class.)
class SaveDetection {
private $proDetection = null;
public function __construct($words) {
$this->proDetection = new ProDetection();
for($i=0;$i<sizeof($words);$i++) {
$this->proDetection->detect($words[$i]);
}
}
public function getScore() {
return $this->proDetection->getScore();\\line 22
}
private $proDetection;
}