I am trying to figure out how to use a method within its own class. example:
class demoClass
{
function demoFunction1()
{
//function code here
}
function demoFunction2()
{
//call previously declared method
demoFunction1();
}
}
The only way that I have found to be working is when I create a new intsnace of the class within the method, and then call it. Example:
class demoClass
{
function demoFunction1()
{
//function code here
}
function demoFunction2()
{
$thisClassInstance = new demoClass();
//call previously declared method
$thisClassInstance->demoFunction1();
}
}
but that does not feel right... or is that the way?
any help?
thanks
$this-> inside of an object, or self:: in a static context (either for or from a static method).
You need to use $this to refer to the current object:
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).
So:
class demoClass
{
function demoFunction1()
{
//function code here
}
function demoFunction2()
{
// $this refers to the current object of this class
$this->demoFunction1();
}
}
Just use:
$this->demoFunction1();
Use $this keyword to refer to current class instance:
class demoClass
{
function demoFunction1()
{
//function code here
}
function demoFunction2()
{
$this->demoFunction1();
}
}
Use "$this" to refer to itself.
class demoClass
{
function demoFunction1()
{
//function code here
}
function demoFunction2()
{
//call previously declared method
$this->demoFunction1();
}
}
Related
I'm trying to call the "this" context within my anonymous function, called inside an object.
I'm running PHP 5.5.9 and the php doc states that "$this can be used in anonymous functions."
What's missing? Should I inject the context in some way binding the function to the object?
<?php
class Example
{
public function __construct()
{}
public function test($func)
{
$func();
}
}
$obj = new Example();
$obj->test(function(){
print_r($this);
});
?>
Output:
PHP Notice: Undefined variable: this on line 18
Well, you actually can use $this in an anonymous function. But you cannot use it outside of an object, that does not make sense. Note that you define that anonymous function outside your class definition. So what is $this mean to be in that case?
A simple solution would be to either define the function inside the class definition or to hand over the $this pointer to the function as an argument.
Solved with this... it definitely horrify me, any other solution (if exists) is well accepted.
<?php
class Example
{
public function __construct()
{}
public function test($func)
{
$func = $func->bindTo($this, $this);
$func();
}
}
$obj = new Example();
$obj->test(function(){
print_r($this);
});
?>
Another solution would be to have $this as an argument of the function, and you just pass it via the call within your class $func($this).
<?php
class Example {
…
public function test($func)
{
$func($this);
}
}
$obj = new Example();
$obj->test(function($this) {
print_r($this);
});
?>
I saw some codes that when they call php functions from another class they no longer use $this->functionName(),
they just refer immedietly to the function name, like functionName()
In my index.php
$help = new Helper();
$help->Test();
I wanted to call Test Function by not doing the $help.
How can this be done? Why is this possible?
In PHP you can mix a procedural style of programming with object oriented style. That means that function can either exist as member of a class, or as stand-alone functions.
Member functions (or methods) are are called using $classinstance->methodname() for normal (instance) methods, or ClassName::methodName() for static methods.
Standalone functions are just called without referring to a class or object whatsoever. You can put them in separate files, if you like.
The declaration and usage is as follows:
In example.php:
class MyClass
{
$member = 'Hello world';
function MyMethod()
{
// The method can use the instance variable (member variable)
// using $this to refer to the instance of the class
echo $this->member;
}
static function MyStaticMethod()
{
echo 'Hello static world';
}
}
function MyFunction()
{
echo 'Hello';
}
In index.php:
// To include the class and its methods, as well as the function.
require_once 'example.php';
// Call an instance method
$instance = new MyClass();
$instance->MyMethod();
// Call a static method
MyClass::MyStaticMethod();
// Call a stand-alone function
MyFunction();
A standalone function is defined like this:
function myfunction() {
# whatever
}
Also see http://www.php.net/manual/en/functions.user-defined.php
With the -> operator you reference a function from within a class.
<?php
class A {
public function a() {
$this->b(); //references the function b() in $this class
}
public function b() {
echo 'Was called from function a() in class A';
}
}
function c() {
echo "I'm just a simple function outside a class";
}
//now you can do following calls
$class_a = new A();
$class_a->a();
c(); //references function c() within the same scope
The output would be:
Was called from function a() in class A
I'm just a simple function outside a class
But you could also do the following: outsource the function c() into an external file like function_c.php
Now, you can include/require the file from anywhere else and use it's content:
include 'function_c.php';
c(); //the function is now available, although it was defined in another file
you can a function from another class from a class, example:
require "myExternClass.php";
class myClass extends myExternClass
{
public function a() {
$this->b(); /* function b is in the class myExternClass */
}
}
generally you can't call a method of an object without the object itself.
but for some cases when method does not actually uses any objects' properties it may be acceptable for testing purposes to invoke it with call_user_func_array, passing some dummy value instead of object.
class A {
var $a;
function doNop() { echo "Nop";}
function doA() { echo "[".$a."]"; }
}
// instead of this
$a = new A;
$a->doNop();
// you _may_ use this
A::doNop();
// but this will fail, because there's no object to apply doA() to.
A::doA();
class A_dummy { $a };
// however, for testing purposes you can provide a dummy instead of real A instance
$b = new A_dummy;
call_user_func(array($b, 'A::doA'));
You can wrap the code in question inside a regular function:
function TestClass() {
$help = new Helper();
return $help->Test();
}
Then, in your index.php file you can call the function like this:
TestClass();
When would you use the $this keyword in PHP? From what I understand $this refers to the object created without knowing the objects name.
Also the keyword $this can only be used within a method?
An example would be great to show when you can use $this.
A class may contain its own constants, variables (called "properties"), and functions (called "methods").
<?php
class SimpleClass
{
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar() {
echo $this->var;
}
}
?>
Some examples of the $this pseudo-variable:
<?php
class A
{
function foo()
{
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")\n";
} else {
echo "\$this is not defined.\n";
}
}
}
class B
{
function bar()
{
// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
}
}
$a = new A();
$a->foo();
// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
$b = new B();
$b->bar();
// Note: the next line will issue a warning if E_STRICT is enabled.
B::bar();
?>
The above example will output:
$this is defined (A)
$this is not defined.
$this is defined (B)
$this is not defined.
The most common use case is within Object Oriented Programming, while defining or working within a class. For example:
class Horse {
var $running = false;
function run() {
$this->running = true;
}
}
As you can see, within the run function, we can use the $this variable to refer to the instance of the Horse class that we are "in". So the other thing to keep in mind is that if you create 2 Horse classes, the $this variable inside of each one will refer to that specific instance of the Horse class, not to them both.
You would only use $this if you are doing Object Oriented programming in PHP. Meaning if you are creating classes. Here is an example:
class Item {
protected $name, $price, $qty, $total;
public function __construct($iName, $iPrice, $iQty) {
$this->name = $iName;
$this->price = $iPrice;
$this->qty = $iQty;
$this->calculate();
}
}
$this is used to make a reference to the current instance of an object.
So you can do things like:
class MyClass {
private $name;
public function setName($name) {
$this->name = $name;
}
//vs
public function setName($pName) {
$name = $pName;
}
}
Also another cool use is that you can chain methods:
class MyClass2 {
private $firstName;
private $lastName;
public function setFirstName($name) {
$this->firstName = $name;
return $this;
}
public function setLastName($name) {
$this->lastName = $name;
return $this;
}
public function sayHello() {
print "Hello {$this->firstName} {$this->lastName}";
}
}
//And now you can do:
$newInstance = new MyClass2;
$newInstance->setFirstName("John")->setLastName("Doe")->sayHello();
It's used in Object-oriented Programming (OOP):
<?php
class Example
{
public function foo()
{
//code
}
public function bar()
{
$this->foo();
}
}
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).
Used for when you want to work with local variables.
You can also read more about it from here.
function bark() {
print "{$this->Name} says Woof!\n";
}
One time I know I end up using the this equivalent in other languages is to implement a 'Fluent' interface; each class method which would otherwise return void instead returns this, so that method calls can be easily chained together.
public function DoThis(){
//Do stuff here...
return $this;
}
public function DoThat(){
//do other stuff here...
return $this;
}
The above could be called like so:
myObject->DoThis()->DoThat();
Which can be useful for some things.
$this is used when you have created a new instance of an object.
For example, imagine this :
class Test {
private $_hello = "hello";
public function getHello () {
echo $this->_hello; // note that I removed the $ from _hello !
}
public function setHello ($hello) {
$this->_hello = $hello;
}
}
In order to access to the method getHello, I have to create a new instance of the class Test, like this :
$obj = new Test ();
// Then, I can access to the getHello method :
echo $obj->getHello ();
// will output "hello"
$obj->setHello("lala");
echo $obj->getHello ();
// will output "lala"
In fact, $this is used inside the class, when instancied. It is refered as a scope.
Inside your class you use $this (for accessing *$_hello* for example) but outside the class, $this does NOT refer to the elements inside your class (like *$_hello*), it's $obj that does.
Now, the main difference between $obj and $this is since $obj access your class from the outside, some restrictions happens : if you define something private or protected in your class, like my variable *$_hello*, $obj CAN'T access it (it's private!) but $this can, becase $this leave inside the class.
no i think ur idea is wrong.. $this is used when refers to a object of the same class.. like this
think we have a variable value $var and in THAT instance of that object should be set to 5
$this->var=5;
The use $this is to reference methods or instance variables belonging to the current object
$this->name = $name
or
$this->callSomeMethod()
that is going to use the variable or method implemented in the current object subclassed or not.
If you would like to specifically call an implementation of of the parent class you would do something like
parent::callSomeMethod()
Whenever you want to use a variable that is outside of the function but inside the same class, you use $this. $this refers to the current php class that the property or function you are going to access resides in. It is a core php concept.
<?php
class identity {
public $name;
public $age;
public function display() {
return $this->name . 'is'. $this->age . 'years old';
}
}
?>
<?php
class Popular
{
public static function getVideo()
{
return $this->parsing();
}
}
class Video
extends Popular
{
public static function parsing()
{
return 'trololo';
}
public static function block()
{
return parent::getVideo();
}
}
echo Video::block();
I should definitely call the class this way:
Video::block();
and not initialize it
$video = new Video();
echo $video->block()
Not this!
Video::block(); // Only this way <<
But:
Fatal error: Using $this when not in object context in myFile.php on line 6
How to call function "parsing" from the "Popular" Class?
Soooooooory for bad english
As your using a static method, you cant use $thiskeyword as that can only be used within objects, not classes.
When you use the new keyword, your creating and object from a class, if you have not used the new Keyword then $this would not be available as its not an Object
For your code to work, being static you would have to use the static keyowrd along with Scope Resolution Operator (::) as your method is within a parent class and its its not bounded, Use the static keyword to call the parent static method.
Example:
class Popular
{
public static function getVideo()
{
return static::parsing(); //Here
}
}
What does $this mean in PHP?
paamayim-nekudotayim - Scope Resolution
http://php.net/manual/en/language.oop5.static.php
change return $this->parsing(); to return self::parsing();
<?php
class jokz {
static public $val='123';
static public function xxx() {
jokz2(self);
}
}
function jokz2($obj) {
echo $obj::$val;
}
jokz::xxx();
?>
it returns fatal error, cause the class "self" couldn't be found...
so.. how can i make that work?
passing a parameter by reference in function also don't work
function jokz2(&$obj) {
echo $obj::$val;
}
There is no object to pass (self refers to static class). You can pass the name of the class and call it that way (using call_user_func) or instantiate an object and pass $this
You would have to use $this to use the current object.