What I think I know so far:
so $this-> is to access a function/var outside its own function/var ?
but how does $this-> know if its a function or a variable ?
why we refer to a var like this $this->data instead of this $this->$data ?
$this refers to the current object that a method has been invoked on. It knows if it's a function if there is a pair of parentheses at the end. We use the former syntax because $this->$data means look at the field whose name is $data; e.g. $this->foo if $data == 'foo'
$this is the variable referring to the object that you are currently inside. $this-> will access either a method or field in the current object.
As for why is it $this->data and not $this->$data, that's just a syntax quirk. You'd have to ask the PHP language designers. It's probably because the latter wouldn't make much sense for a method.
If this looks like Greek to you, then you may want to head over to the PHP manual's section on classes and objects and read up.
$this represents the instance of a given object, from the context of within the object.
I would say, knowing whether you're accessing a method or property is your responsibility. Read documentation. If you're calling an object method using this, it uses the expected syntax of $this->method($args); and properties (member variables) use the expected syntax of $this->var = 'value';
It's a pretty long subject, but in sort, $this is a pointer to an instance. $this->data refers to the data variable of a particular instance(this instance). It is $this->data and not $this->$data just because of convention.
Related
I understand that static methods have no access to state of instance objects of their class types and hence referencing $this inside them results in an error.But objects can reference static methods using object to member operator ->
$obj->staticMethod();
and can even pass it their state via paramaters.
$para1 = $obj->para1;
$para2 = $obj->para2;
$obj->staticMethod($para1, $para2);
How is this last example possible when statics are resolved in static context. If someone can explain to me the general behaviour of statics in php code. you can even talk about C related concepts if it will help.
Since you state that you already understand what static means, I'll skip over that.
However, it may still be good to reference PHP's documentation on the static keyword. In particular the following two alerts are important (and hard to glance over, really).
Caution In PHP 5, calling non-static methods statically generates an E_STRICT level warning.
And this one (italic emphasis mine).
Warning In PHP 7, calling non-static methods statically is deprecated, and will generate an E_DEPRECATED warning. Support for calling non-static methods statically may be removed in the future.
So, to cut a long story short: yes, your example will run (for now), because the PHP interpreter will try to fix up your mistake for you. You should however never do this. What the PHP interpreter will do is:
Say your $obj is of type Foo. Then it will read
$obj->staticMethod($para1, $para2);
conclude that staticMethod is static and instead execute
Foo::staticMethod($para1, $para2);
It is of course perfectly fine to pass parameters that are properties of an instance of Foo. It doesn't matter to staticMethod where the parameters come from.
To elaborate a bit more on why this works, while using $this in a static method is not allowed.
You can think of normal methods as static functions that have one extra: they receive an implicit parameter $this. The value of $this is simply the object on which the method is called. Thus, $obj->do($a, $b, $c) is equivalent to calling Foo::do($obj, $a, $b, $c) and naming the first argument of do, $this. This is convenient, because we can now easily define methods that work on an instance of an object without having to explicitly state over and over again that this instance is a parameter of our methods. Great.
Now back to static functions. The only difference with normal methods is that they do not receive this implicit $this parameter. Thus, using $this inside of them is invalid. Not because it is forbidden, but because it does not reference anything. PHP does not (and cannot) have a clue what $this should refer to.
Another way to look at it. Say that our Foo class has two properties: $para1 and $para2, both numbers. Say that you write a method that returns the sum of these numbers. One way is to do this:
public static function sum($para1, $para2) {
return $para1 + $para2;
}
Great. Works. However, it is annoying to have to call it like this
$sum = Foo::sum($obj->para1, $obj->para2);
So, this is what methods are for!
public function sum(/* implicit $this parameter */) {
// write looking up the properties once inside the function, instead
// of having to write it every time we call the function!
return $this->para1 + $this->para2;
}
// ...
$sum = $obj->sum(); // $obj is passed implicitly as $this
Because static functions do not receive an implicit $this parameter, using $this inside of them is like trying to use $undefined when you have never defined it. Thus, invalid.
Static means class members in simple terms , A static data member is accessible within a class regardless object is created or not . The static function are also functions dedicated to whole class . Static function works with static data only bit it can sometimes vary . Though statics are class dedicated, you can access them using object. It is allowed in all languages. Why ? Because of feasibility . If an object is not being able to access static members , that is a limitation.
Alright so I think this may be extremely basic, but it has me stumped nonetheless. Before I get to my question, let me demonstrate the concept my question is based on with this working example:
<?php
$a = 'Stack';
$b = $a.' Overflow';
echo $b; // Result: "Stack Overflow"
?>
In the above example, $b is defined as the combination of $a and ' Overflow'.
Now, let's assume I want to do the same thing as above except I don't want to use global variables. I want to use classes. This is how I have attempted to achieve that:
<?php
class ClassName {
public $a = 'Stack';
public $b = $this->a.' Overflow'; // This gives me: "Parse error: syntax error, unexpected '$this'"
}
$instantiate = new ClassName;
echo $instantiate->$b; // Desired result: "Stack Overflow"
?>
As stated, this attempt results in an error. To me, this attempt seems logical, but I guess PHP doesn't think so.
Question: Is this possible, and if so, how do I go about achieving the desired result? Also, if you could explain why my attempt has failed (logically), that would be a bonus.
I've searched and researched for hours on end trying to find an answer or figure this out on my own, but for the life of me, I cannot find anyone or anything that even touches on this (including other Stack Overflow threads). I can't even find anywhere saying it's impossible or anything of the sort either.
I'm a PHP novice, so I may need more explanation than others, but any kind of help or general guidance would be much appreciated. Thank you.
You cannot use $this when defining the class because it refers to a concrete object context which becomes available after instantiation. You can use a constructor for that kinds of stuff.
class ClassName
{
public $a = 'Stack';
public $b = "";
function __construct()
{
$this->b = $this->a.' Overflow';
}
}
$instantiate = new ClassName;
echo $instantiate->b;
Quoting from the PHP Docs about defining class properties
They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value -- that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
(my emphasis)
Concatenation cannot be evaluated at compile time, only at run time.
If you need to do this, then define the initial value for the property in the constructor
This would throw a syntax error because you are using $this in a scope that it is not allowed to:
The pseudo-variable $this is available inside any class method when that 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).
This means, even if you wanted you won't be able to do what you want to do because of such restriction. This is a common restriction that is in many programming languages, properties have to be initialized to static values. To solve your issue you can do any of the following:
In your constructor, create those variables.
Create the second variable on its own, and create a method that concatenates the two.
Create a magic method to do it for you.
The same restriction holds true for static class properties.
An old colleague of mine wrote this in our code:
public function paginate() {
return $this->paginate;
}
And I was wondering: does this return the function paginate() or the class property $paginate?
I'm guessing the latter, but it is strange that I haven't found any information on this subject.
That returns the class property $paginate.
If it was return $this->someName();
then it returns function someName().
The brackets after a function call in PHP aren't optional, and ordinary methods and functions are not "first class objects" (they can't be manipulated as variables in their own right, as for instance, in JavaScript).
Thus there is no ambiguity, since $this->paginate(); must be a function call, and $this->paginate; must be a variable reference.
However, it is not particularly good practice, and editors, IDEs, etc, will probably highlight it as a warning.
Common practice is for functions and methods to begin with a verb (what it does), and property names to be a noun (what it is). So the property should probably be "pagination", and the method either "paginate" (take the data and create some pagination), or "getPagination" (return the "pagination" property).
Return an object property:
$this->paginate;
vs
Cause an object method to run (function in a class is termed a method)
$this->paginate();
It will return the $paginate property of the class that the function belongs to or ihnerits from another class, if it is declared as public.
why does this not work ?
class Test{
private $vars = array('ALL' => 0,
'ONE' => 1);
private $var = $vars['ALL']; // this does not work
function __construct(){
$this->var = $vars['ALL']; // this does work
}
}
code example here: http://codepad.org/QSjHMDij
why is the array not accessible in the statement
private $var = $vars['ALL']; // this does not work
Probably because you can't access $this during the initialization of the class prior to the constructor getting called (which is implied when you tried to do it in the definition for $var.) Some languages (like C#) will let you do it, but I think PHP is one that will not.
Neither "works" in the way you intend. You are not allowed to use variables when declaring instance members (hence the unexpected T_VARIABLE error). In the constructor you are referencing a local variable named $vars which does not exist, meaning you're setting $this->var to NULL.
Access the instance member by doing $this->vars. You can only do this in the constructor.
When declaring members (variables), you can't assign array key values of other members, it causes a parse error.
For example, you're thinking (wrong) that $vars['ALL'] is referring to your private $var - which it is not - it also causes a parse error. There's no way for PHP to know that when you say:
private $var = $vars['ALL'];
that you're actually saying "I want value of $this->vars['ALL'] to be assigned to $this->var", at least not the way you wrote it. That's why you do that from within a function, where you can easily manipulate members, such as you did from the constructor.
You should declare members, their visibility and set some default values (like you did for $var), but you shouldn't point them to other members' values, it's simply - wrong and luckily - it doesn't work :)
You're trying to assign a value to a variable which is designed to be part of an object, rather than the class. What you want is static variables.
Please stop me if i am doing something wrong. It works but somehow it doesn't appear the right way to me... Look at the member function call in talks.php. Does this look right to you? Is there a better way to solve that? Thanks.
show.php
I am passing my user class by reference:
$talks = new talks($comments, $user);
talks.php:
[...]
function __construct($comments, &$user)
{
//Passing user class
$this->user = $user;
[...]
if ($this->user->is_loaded()){}
This looks a-ok to me. What problem do you see with it?
In php 5, objects are always passed by reference.
From http://www.php.net/manual/en/language.oop5.references.php:
A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.
So, you should not need the "&" operator in the parameter list of your constructor.