PHP: meaning of 'thing' with two uses of -> - php

Possible duplicate of Reference - What does this symbol mean in PHP?
What does it mean when you have something like this $this->_view->id ?
It is within a class (obviously) and I understand the $this. I get how to use one -> to refer to a property or call a method. But what about when there are two -> in one thing?
The fuller code is:
$viewid = ($this->_view) ? $this->_view->id : null;
I'm guessing the overall gist is: Set $viewid to either (1) the value of $this->_view->id or (2) null, depending on whether $this->_view is TRUE or not. But I don't get the (1) bit.
Also, is it conventional to use an underscore (_view) to show a property or a method?
Thanks.

This means that there is an object stored within an object.
$this->_view refers to an object called $_view within. So within $_view object $this->id would refer to its $id variable.
So calling $this->_view->id calls for variable $id in an object $_view that is stored in your current object (since you said its $this).
Detailed:
class firstClass {
public $_view;
}
class secondClass{
public $id=1;
}
$a=new firstClass();
$a->_view=new secondClass();
echo $a->_view->id; // prints 1

$viewid = ($this->_view) ? $this->_view->id : null;
It means if view object is available for current object, then set its id to $viewid, otherwise set it to null.
for example $this is current object of UserClass. $this->_view is object of view of UserClass and $this->_view->id is id of view object.
Generally, for private or protected member of class, we start with _

$id is attached to an object returned by the function function _view.
The underscore is a preference,

Related

What is the difference in this way of method calling

As I got it, in the first example an object is created, and in the second one I don't see an object created. I am trying to understand, what is the difference between the two ways of method calling :
<?php
class Animal{
public $voice;
public function speak($sound){
echo $this->voice = $sound;
}
}
// Example 1
$tiger = new Animal();
$tiger->speak('Roar');
// Example 2
(new Animal)->speak("Cloak Cloak");
Whenever you use "new", you're creating an instance of an object (it can be temporary). The difference in your code is that in the first example, you're storing the instance in "$tiger", so it'll persist, but in the second example you're only instantiating a temporary object to call a method.
In the first example, you are assigning the variable $tiger as a new Object, by which you can then call the functions and variables associated with that object, by referencing $tiger.
i.e. as Tiger now equals an Object of Class Animal, it can speak.
However in the second example, you are still creating a new Object of class Animal, and as such it can speak - but you have not assigned it to a variable. So you cannot reference that same Object any longer.
So in the first example, if we wanted to name our $tiger, we could have the Class look something like this.
class Animal{
public $voice;
public $name = "I have no name.";
public function speak($sound){
echo $this->voice = $sound;
}
public function sayYourName(){
echo $this->name;
}
}
Now if we say,
$tiger = new Animal();
$tiger->speak('Roar');
$tiger->name = "Rory";
$tiger->sayYourName(); // This will echo "Rory"
However, if you try your second example instead :
(new Animal)->sayYourName(); // This will echo "I have no name."
So if you say :
(new Animal)->name = "Rory";
(new Animal)->sayYourName(); // This will still echo "I have no name".
This is because we haven't assigned a reference to the new animal, so while we can access methods of the function, and even predefined variables, we can't then reference them again later on.
To do that, we should stick to the first method (i.e. referencing)
$tiger = new Animal();
$tiger->name = "Rory";
$tiger->sayYourName();
In conclusion, use referencing to refer to an Object later on. i.e to get the animals attention, you have to call it by its name.

$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.

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

What is wrong with this PHP static Method?

I have declared a static method in class category
public static function getPrefixFromSubCategoyId($subCategoryId) {
$prefix = $this->fetch(array('table' => 'subCategories', 'id' => $subCategoryId));
return $prefix[0]['prefix'];
}
i am sure that i am using correct piece of code because when i use the same code outside the class scope with following code it works properly
$category = new Category($dbh);
$subCategoryId = 6;
$prefix = $category->fetch(array('table' => 'subCategories', 'id' => $subCategoryId));
echo $prefix[0]['prefix'];
but when i initialize the static method with following syntax.
$prefix = Category::getPrefixFromSubCategoyId(4);
it gives me following error.
Fatal error: Using $this when not in object context
am i missing something? or am i declaring it the wrong way?
thank you..
static methods are class members and aren't bound to an object. This means, that $this simply doesn't exists. You cannot use it in static methods. If fetch() is static too, call it static
self::fetch(/* arguments */);
If not either getPrefixFromSubCategoyId() should not be static too, fetch() should be static (see example above), or you need an object
$tmp = new self;
$tmp->fetch(/* arguments */);
$this is a reference to the current object. It is not the reference to the class. Since you are using it statically you have no object. You would have to make a static call in there as well.
$this is used to get instance variables or methods (simple members and basically the current object if you have one defining with new) but when you want to reach the static variables you should use $self::some_varible and :: is scope resolution operator.
You must declare your methods or variables static if you do want to use them under a static function.

What is the difference between `$this->name` and `$this->$name`?

I am wondering what is the difference between $this->name and $this->$name? Also does $this have to be strictly named this or can it be anything?
$this is a reserved variable name and can not be used for anything else. It specifically points you to the object your are currently working in. You have to use $this because you do not know what variable object will be assigned to.
$this->name refers to the current class's variable name
$this->$name refers to the class variable of whatever the value of $name is. Thus
$name = "name";
echo $this->$name; // echos the value of $this->name.
$name = "test";
echo $this->$name; // echos the value of $this->test
$this is a reserved name used in PHP to point to the current instance of the class you are using it in (quoting) :
The pseudo-variable $this is available
when a method is called from within an
object context. $this is a reference
to the calling object (usually the
object to which the method belongs,
but possibly another object, if the
method is called statically from the
context of a secondary object).
When using $this->name, you are accessing the property with the name name of the current object.
When using $this->$name, $name is determined before accessing the property -- which means you'll access the property which name is contained in the $name local variable.
For instance, with this portion of code :
$name = 'abc';
echo $this->$name;
You'll actually echo the content of the abc property, as if you had written :
echo $this->abc;
When doing this, you are using variable variables (quoting) :
Class properties may also be accessed
using variable property names. The
variable property name will be
resolved within the scope from which
the call is made. For instance, if you
have an expression such as $foo->$bar,
then the local scope will be examined
for $bar and its value will be used as
the name of the property of $foo. This
is also true if $bar is an array
access.
This question just popped up after an update. I liked the question, so I thought I'd add my own example of the difference.
class Test
{
public $bar = 'bar';
public $foo = 'foo';
public function __construct()
{
$bar = 'foo';
$this->bar; // bar
$this->$bar; // foo
}
}

Categories