In PHP 5, what is the difference between using self
and $this
?
When is each appropriate?
In PHP 5, what is the difference between using self
and $this
?
When is each appropriate?
You can't define a class in another class. You should include files with other classes outside of the class. In your case, that will give you two top-level classes db
and some
. Now in the constructor of some
you can decide to create an instance of db
. For example:
include SITE_ROOT . 'applicatie/' . 'db.class.php';
class some {
public function __construct() {
if (...) {
$this->db = new db;
}
}
}
include global $myarray
at the start of setvalue()
function.
public function setvalue() {
global $myarray;
$myvalue = $myarray[0];
}
UPDATE:
As noted in the comments, this is bad practice and should be avoided.
A better solution would be this: https://.com/a/17094513/3407923.
It is idiomatic to prefer to omit self.
when invoking methods; it is generally never needed.
You must use self.foo = xxx
when calling a setter method, instead of foo = xxx
, so that Ruby realizes that you are not trying create a new local variable.
do_something
with the same name as a method, you must use self.do_something
to invoke the method, as just do_something
will end up reading the variable.You cannot use self.foo(...)
to call a private method; you must instead call just foo(...)
.
When you're doing an action on the instance that's calling the method, you use self.
With this code
class SocialData < ActiveRecord::Base
def set_active_flag(val)
active_flag = val
save!
end
end
You are defining a brand new scoped local variable called active_flag, setting it to the passed in value, it's not associated with anything, so it's promptly thrown away when the method ends like it never existed.
self.active_flag = val
However tells the instance to modify its own attribute called active_flag, instead of a brand new variable. That's why it works.
Short Answer
Full Answer
Here is an example of correct usage of
$this
andself
for non-static and static member variables:Here is an example of incorrect usage of
$this
andself
for non-static and static member variables:Here is an example of polymorphism with
$this
for member functions:Here is an example of suppressing polymorphic behaviour by using
self
for member functions:From http://www.phpbuilder.com/board/showthread.php?t=10354489:
By http://board.phpbuilder.com/member.php?145249-laserlight