I am calling a function inside a class, function is outside the class. I want to pass $this of the class to that function,
currently I am doing this:
class foo {
func_outside_class($this);
}
function func_outside_class($context){
return $context;
}
Is there a way so that I don't need to pass context as function parameter.
Or my above code is OK?
I cannot create an object inside function, cause this class need some parameters.
#Barmar wrote:
There's nothing wrong with passing $this to an outside function. But I don't understand why you're immediately overwriting the $context variable -- why does the function take an argument if it's not using it? Perhaps you mean $this = $context.
If that's that case, I don't think you can do it. You're not allowed to assign $this, it's a special variable that always contains the current object in a class method.
In the outside function, you can simply do $context->method(...) to use it instead.
If you're trying to just reference methods inside of you class you can do something like this
class Foo {
public function bar() {
return 'Hello World';
}
}
function func_outside_class() {
// instantiate class
$foo = new Foo;
// call method bar() from Foo class
echo $foo->bar();
}
Related
I currently am using PHP and was reading the PHP manual but still have a problem with $this.
Is $this something global or is it is just another variable name to build objects on?
Here is an example:
public function using_a_function($variable1, $variable2, $variable3)
{
$params = array(
'associative1' => $variable1,
'associative2' => $variable2,
'associative3' => $variable3
);
$params['associative4'] = $this->get_function1($params);
return $this->get_function2($params);
}
How would $this work for the return function? I guess I am confused on how this function builds. I understand building the associate array part with a name being a valuekey names => value, but $this throws me off on this example.
$this is only used in object oriented programming (OOP) and refers to the current object.
class SomeObject{
public function returnThis(){
return $this;
}
}
$object = new SomeObject();
var_dump($object === $object->returnThis()); // true
This is used inside the object to reach member variables and methods.
class SomeOtherClass{
private $variable;
public function publicMethod(){
$this->variable;
$this->privateMethod();
}
private function privateMethod(){
//
}
}
It is refered to as the Object scope, lets use an example class.
Class Example
{
private $property;
public function A($foo)
{
$this->property = $foo;
// we are telling the method to look at the object scope not the method scope
}
public function B()
{
return self::property; // self:: is the same as $this
}
}
We can now instance our object and use it in another way also:
$e = new Example;
$e::A('some text');
// would do the same as
$e->A('some other text');
This is just a way of accessing the scope of the Object because methods cannot access other method scopes.
You can also extend a class and use the parent:: to call the class extension scope, for example:
Class Db extends PDO
{
public function __construct()
{
parent::__construct(....
Which would access the PDO construct method rather than its own construct method.
In your case, the method is calling other methods that are in the object. Which can be called using $this-> or self::
I have a class setup like this:
class myClass {
public function __construct() {
echo 'foo bar';
}
}
To run it, I can simply do:
$object = new myClass;
Is there any way to run the class so __construct initiates without creating a new variable with the class object.
For example, a basic function can be run with:
functionname();
Don't call __construct directly. If you need something in the constructor to occur but you don't want an object created as a result, then use a static method.
class Thing{
public static function talk(){echo "I talk";}
}
Thing::talk(); // 'I talk'
Static methods can be called without the need for an object instance of the class.
__construct is part of a special group of methods in PHP, called Magic Methods. You don't call these directly, but PHP will call them when some event occurs. For instance when you call new on a class, __construct is executed.
Another example: if you try to get a property that doesn't exist, __get will be executed (if found):
Class Thing{
public property $name = 'Berry';
public function __get($propertyName){
return "$propertyName does not exist!";
}
}
$t = new Thing();
echo $t->name; // 'Berry'
echo $t->weight; // 'weight does not exist!';
You can try something like this if you want to avoid static:
(new MyClass)->myFunction();
I have no idea why you need this but you don't need to create a variable. You can just create object without store it anywhere.
class myClass {
public function __construct() {
echo 'foo bar';
}
}
new myClass();
In this case only the constructor will be call.
I have a class with a few methods that take an anonymous function as a parameter. The class looks like this:
class MyClass {
public function myMethod($param, $func) {
echo $param;
user_call_func($func);
}
public function sayHello() {
echo "Hello from MyClass";
}
}
I'd like to be able to do things like this:
$obj = new MyClass;
$obj->myMethod("Hi", function($obj) {
echo "I'm in this anonymous function";
// let's use a method from myClass
$obj->sayHello();
});
So, in my anonymous function, since I passed $obj as a parameter to the anonymous function, I should be able to access its methods from within the anonymous function. In this case we'd see
I'm in this anonymous function
Hello from MyClass
How would I achieve this?
Thanks
Use the use construct:
$self = $this;
$obj->myMethod("Hi", function($obj) use($self) {
echo "I'm in this anonymous function";
// let's use a method from myClass
$obj->sayHello();
});
You've got to capture $this in another variable because use doesn't allow $this to be passed in, unless you are using PHP >= 5.4. Relevant quote from the documentation:
Closures may also inherit variables from the parent scope. Any such
variables must be passed to the use language construct. Inheriting
variables from the parent scope is not the same as using global
variables. Global variables exist in the global scope, which is the
same no matter what function is executing. The parent scope of a
closure is the function in which the closure was declared (not
necessarily the function it was called from).
Update
It may also be helpful to know that you retain the visibility of the class that you're currently in when the anonymous function is executing, as demonstrated in this simple script:
class Test
{
public function testMe()
{
$self = $this;
$tester = function() use($self) {
$self->iAmPrivate();
};
$tester();
}
private function iAmPrivate()
{
echo 'I can see my own private parts!';
}
}
$test = new Test;
$test->testMe();
Output:
I can see my own private parts!
Why can't bee() call bar() unless I prepend self:: ?
class X {
function bar ()
{
echo "OK";
}
public static function bee ()
{
bar ();
}
};
$x = new X ();
$x->bee ();
static functions do not have access to the $this pointer, but what you have written there is actually trying to call the global function bar(). A regular call to a method on $x would be something like:
class X
{
...
static function Bee()
{
$this->Bar();
}
}
but this is not good practice because then your static function depends on being called from an object and there is no point in having it be static.
http://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods
As mentioned above, a method may be
declared as static, meaning that it
acts at the class level rather than at
the instance level. Therefore, a
static method cannot refer to a
specific instance of the class (i.e.
it cannot refer to this, self, Me,
etc.), unless such references are made
through a parameter referencing an
instance of the class, although in
such cases they must be accessed
through the parameter's identifier
instead of this. Most importantly
there is no need to make an object for
accessing data .i.e. without creating
an object we can access the data
members of a static class.
you are insight of a static method.
Inside of a static method you are not in the object context so you cannot call the method with $this, ...
self::bar() or X::bar (); does the job...
But be carefull. Stuff like that is not possible if you call it from a static method:
function bar ()
{
echo $this->test;
}
I would not make the method static unless you need it!
BR,
TJ
Static methods get called via the scope resolution operator ::
X::bee();
Then inside bee() you call bar(), what is a regular function, not a method. Here you must call it the same way as mentioned above, but you can simplify the scope identifier to self
public static bee () {
self::bar();
}
Just to remember: Every "function" inside a class is in real a method. If you omit the visibility identifier public is implicitly assumed, but it will remain a method and must be called like this.
I see bar() is not static. To call a regular method you need an instance of the object within the context you are going to call it. Here you can either make bee() non-static (then $this as reference to the current object is avaible), or you instanciate a new object within bee().
class X {
public function bar () { /* .. */ }
public function bee () { $this->bar(); }
}
$x = new X;
$x->bee();
or
class X {
public function bar () { /* .. */ }
public static function bee () {
$x = new self();
$x->bar();
}
}
X:bee();
Whats better depends on what the methods should do (meaning: Whats the design of the class in whole):
I have a question regarding static function in php.
let's assume that I have a class
class test {
public function sayHi() {
echo 'hi';
}
}
if I do test::sayHi(); it works without a problem.
class test {
public static function sayHi() {
echo 'hi';
}
}
test::sayHi(); works as well.
What are the differences between first class and second class?
What is special about a static function?
In the first class, sayHi() is actually an instance method which you are calling as a static method and you get away with it because sayHi() never refers to $this.
Static functions are associated with the class, not an instance of the class. As such, $this is not available from a static context ($this isn't pointing to any object).
Simply, static functions function independently of the class where they belong.
$this means, this is an object of this class. It does not apply to static functions.
class test {
public function sayHi($hi = "Hi") {
$this->hi = $hi;
return $this->hi;
}
}
class test1 {
public static function sayHi($hi) {
$hi = "Hi";
return $hi;
}
}
// Test
$mytest = new test();
print $mytest->sayHi('hello'); // returns 'hello'
print test1::sayHi('hello'); // returns 'Hi'
Entire difference is, you don't get $this supplied inside the static function. If you try to use $this, you'll get a Fatal error: Using $this when not in object context.
Well, okay, one other difference: an E_STRICT warning is generated by your first example.
Calling non-static methods statically generates an E_STRICT level warning.
In a nutshell, you don't have the object as $this in the second case, as
the static method is a function/method of the class not the object instance.
After trying examples (PHP 5.3.5), I found that in both cases of defining functions you can't use $this operator to work on class functions. So I couldn't find a difference in them yet. :(