Create an instance of an object inside a method - php

I read a book on OOP PHP, can not understand what the author means:
class Registry {
/**
* Array of objects
*/
private $objects;
public function createAndStoreObject($object, $key) {
require_once($object.'.class.php');
$this->objects[$key] = new $object($this);
}
}
1) $this->objects[$key] - We saving a private class array value.
2) new $object($this) - I do not understand where we take the object $object (if this array) and what is meant in the sense of $this?

$class = 'Foo';
$foo = new $class;
is the same as
$foo = new Foo;
That explains what new $object does. And while it's instantiating a new instance of whatever $object is, it is passing $this to the object's constructor. I.e. it's passing a reference to the Registry object to the object that is being constructed.

It is example of Registry Design Pattern, which creates objects similar as the Factory Design Pattern. In this pattern, a class simply creates the object you want to use without necessarily knowing what kind of object it creates. In your example createAndStoreObject function creates a new instance of a class using a variable class name.
If, for example, $object = 'Foo', then is the same as:
require_once('Foo'.'.class.php');
$this->objects[$key] = new Foo($this);
The meaning of $this passed to the constructor is that all objects created can have access to the Registry object

$this refers to the current object within scope so in your case the Registry class so you could call to the $object variable within the scope of you class by using $this->objects

Related

How to access a class property that is of type object in PHP?

I know how to access an object's property if the property type is a simple string
class My_Class {
public $var = 'Hello';
// More stuff...
}
$obj = new My_Class();
echo $obj->var
But imagine if My_Class::var was type object which itself had properties. How would I access one of those properties?
Just continue working your way down the chain like so:
$obj->var->property_name;
The same way you'd access a regular object but working through the instance of the container class. For example:
$obj->var->some_method() or $obj->var->some_public_property;

php - setter of objects is not called

I have the following issue:
The current code of an application I'm working on contains a very large number of definitions like this:
$obj = new stdClass();
$obj->a->b = "something";
This results in: PHP Strict Standards: Creating default object from empty value in [somewhere].
The correct form would be:
$obj = new stdClass();
$obj->a = new stdClass();
$obj->a->b = "something";
Now the problem: Replacing this throughout the code would take ages (consider thousands of cases, with conditions, etc.).
So I was thinking of replacing stdClass with a custom object (this would be a simple replace in code), creating a setter for it that verifies if the variable property is an object, and defines it as object if it is before setting the second property.
So we get:
class MockObject() {
public function __set($property, $value) {
// Do stuff here
}
}
$obj = new MockObject();
$object->a->b = "something";
The problem is that when executing $object->a->b = "something"; setter is not called (because you don't actually set the a property, but the b property).
Is there any way around this? Or is other solution possible?
Note: Explicitly calling the __set() method is not a solution since it would be the same as defining properties as stdClass().
You know about the magic setter.
Use a magic getter also.
If it wants to get a var that does not exists: create one (in an array or something like that) that is an instance of that class.
Why don't you initialize your b variable in the constructor of the A class ?
public function __construct()
{
$this->b = new B();
}

$this acting alone in the php code

I have been confused by $this.I know $this->somevaribale used for refering global values...But i have seen a code like
class ClassName
{
private $array; //set up a variable to store our array
/*
* You can set your own array or use the default one
* it will set the $this->array variable to whatever array is given in the construct
* How the array works like a database; array('column_name' => 'column_data')
*/
function __construct($array = array('fruit' => 'apple', 'vegetable' => 'cucumber')) {
$this->array = $array;
}
/*
* Loops through the array and sets new variables within the class
* it returns $this so that you may chain the method.
*/
public function execute() {
foreach($this->array AS $key => $value) {
$this->$key = $value; //we create a variable within the class
}
return $this; //we return $this so that we can chain our method....
}
}
Here $this is called alone ...Am really confused with this..When i remove $this and replaced with $this->array i get error..
So my question is what is the use of calling $this alone and what it represents.
Thanx for the help.
$This is a reference for PHP Objects. You can learn more about objects and how $this works in the PHP manual here.
A class is a kind of "blueprint" of an object, and vice versa, and object is an instance of a class. When $this is used within the class, it refers to itself.
$hi = new ClassName();
$hi->execute()->method()->chaining()->is_like_this();
$hi refers to a ClassName object, and the function execute() returns the object itself.
$ha = $hi->execute();
// $ha refers to a ClassName object.
Method chaining (fluent interfaces) enables one to tidy up the code if one normally calls many methods of that object:
$hi->doSome();
$hi->doAnotherThing();
$hi->thirdMethodCall();
$hi->etcetera();
will become
$hi->doSome()
->doAnotherThing()
->thirdMethodCall()
->etcetera();
A couple of corrections to the terms you use:
$this is a reference to the "current" object, not "global values"
you're not "calling" anything here; functions are called, you're just using $this (which, again, is a variable holding an object)
So, return $this returns the current object as return value of the method. This is usually just done to facilitate fluent interfaces, a style where you can write code like:
$foo->bar()->baz()
Because bar() returns an object (the $this object), you can call its method baz() right afterwards.

Static instance array in instance method

The I18n class in CakePHP provides this method to create instances:
public static function getInstance() {
static $instance = array();
if (!$instance) {
$instance[0] = new I18n();
}
return $instance[0];
}
Among other considerations (please correct me if I'm wrong), I understand it helps to use class instances from the convenience functions:
/**
* Returns a translated string if one is found; Otherwise, the submitted message.
*/
function __($singular, $args = null) {
// ...
$translated = I18n::translate($singular);
// ...
}
echo __('Hello, World!');
This looks cleaner than having to pass the instance around as argument (or, even worse, using a randomly named global variable). But I can't imagine a reason why $instance is an array rather than a plain object.
What can be the purpose of using a one-item array to store class instances?
I would suspect this to be leftovers from older PHP4/CakePHP versions where the instances were assigned by reference.
https://github.com/cakephp/cakephp/blob/1.2.0/cake/libs/i18n.php
function &getInstance() {
static $instance = array();
if (!$instance) {
$instance[0] =& new I18n();
$instance[0]->l10n =& new L10n();
}
return $instance[0];
}
$_this =& I18n::getInstance();
Assigning by reference doesn't work with static, the reference is not being remembered, but it works when assigned to an array entry.
So this was most probably just a workaround for a PHP limitation.
One possible reason for this is to keep all singleton class instances in one global - (static is a synonym of global in this case) array variable for monitoring or not messing the global/local namespace with individual variables for each singleton. If each of the static variables were with random names e.g $translated it would be more easier to overwrite and mess its value. - bug again for me, this is extremely rear possibility.
For example the I18Nn instance would be with [0] key, other class would have other key. You should check outher singleton classes how manage the static $instance array values.

PHP combine $this variable

How to combine two variables to obtain / create new variable?
public $show_diary = 'my';
private my_diary(){
return 1;
}
public view_diary(){
return ${"this->"}.$this->show_diary.{"_diary()"}; // 1
return $this->.{"$this->show_diary"}._diary() // 2
}
both return nothing.
Your class should be like following:
class Test
{
public $show_diary;
function __construct()
{
$this->show_diary = "my";
}
private function my_diary(){
return 707;
}
public function view_diary(){
echo $this->{$this->show_diary."_diary"}(); // 707
}
}
It almost looks from your question like you are asking about how to turn simple variables into objects and then how to have one object contain another one. I could be way off, but I hope not:
So, first off, what is the differnce between an object and a simple variable? An object is really a collection of (generally) at least one property, which is sort of like a variable within it, and very often functions which do things to the properties of the object. Basically an object is like a complex variable.
In PHP, we need to first declare the strucutre of the object, this is done via a class statement, where we basicaly put the skeleton of what the object will be into place. This is done by the class statement. However, at this point, it hasn't actually been created, it is just like a plan for it when it is created later.
The creation is done via a command like:
$someVariable= new diary();
This executes so create a new variable, and lays it out with the structure, properties and functions defined in the class statement.
From then on, you can access various properties or call functions within it.
class show_diary
{
public $owner;
public function __construct()
{
$this->owner='My';
}
}
class view_diary
{
public $owner;
public $foo;
public function __construct()
{
$this->foo='bar';
$this->owner=new show_diary();
}
}
$diary= new view_diary();
print_r($diary);
The code gives us two classes. One of the classes has an instance of the other class within it.
I have used constructors, which are a special type of function that is executed each time we create a new instance of a class - basically each time we declare a variable of that type, the __construct function is called.
When the $diary= new view_diary(); code is called, it creates an instance of the view_diary class, and in doing so, the first thing it does is assigns it's own foo property to have the value 'bar' in it. Then, it sets it's owner property to be an instance of show_diary which in turn then kicks off the __construct function within the new instance. That in turn assigns the owner property of the child item to have the value 'My'.
If you want to access single properties of the object, you can do so by the following syntax:
echo $diary->foo;
To access a property of an object inside the object, you simply add more arrows:
echo $diary->owner->owner;
Like this?
$diary = $this->show_diary . '_diary';
return $this->$diary();

Categories