Php this inside function

PHP «this» context in anonymous function

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?

 public function test($func) < $func(); >> $obj = new Example(); $obj->test(function()< print_r($this); >); ?> 
PHP Notice: Undefined variable: this on line 18 

I know this question is a bit old but may I know where in the docs has it been stated so that: «$this can be used in anonymous functions.»? I’ve encountered this and I wanted to verify it from the docs but found nothing, then found your question using Google. Is it really in the official documentation?

3 Answers 3

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.

I was dreaming about the php engine auto passing the right context basing upon where the function was called. But I realized right now how this would be a stupid and error prone thing. you’re right!

Источник

Вызвать $this внутри функции

поскольку тут (к счастью) не все знакомы с WP, то объясните всю логику, которую вы хотите реализовать. Можете заюзать анонимную функцию, оно конечно не будет видно снаружи класса, как ваша текущая реализация. То есть пока что ваш класс и ваша функция вообще никак не связаны.

объявить как public static $array = . , использовать как ClassName::$array , но в таком случае массив один для всех экземпляров класса, но мне кажется у вас класс создается только единожды.

1 ответ 1

В вашем коде у вас имеется класс, в котором определены функции. В данных функциях, вы обяъвляете другие функции. Это просто объявления, к самому классу они не будут никак относится. После вызова метода Init у вас все так же будет оставаться класс, а также для вызова в других местах кода станет доступна функция add_class .

Замечу, что при повторном вызове функции init интерпретатор упадет с ошибкой fatal error при попытке объявить заново функцию add_class .

Поскольку объявленная функция ни коим боком не будет относится к классу (который ее объявил), то, конечно, речи о доступе к $this там быть не может. О чем и сказано в сообщении об ошибке.

Читайте также:  Vector in java with examples

Как вариант решения (если используете данный массив единственном экземпляре) может стать объявление массива как статического члена класса.

В дальнейшем для обращения к массиву из сторонних функций будут иметь следующий вид:

foreach( ClassName::$array as $class )

Повторюсь, что статические свойства существуют в единственном экземпляре и одинаковы межде всеми экземплярами класса. Но по всей видимости, класс у вас используется тоже в единственном экземпляре.

Источник

What does the variable $this mean in PHP?

I see the variable $this in PHP all the time and I have no idea what it’s used for. I’ve never personally used it. Can someone tell me how the variable $this works in PHP?

11 Answers 11

It’s a reference to the current object, it’s most commonly used in object oriented code.

name = $name; > >; $jack = new Person('Jack'); echo $jack->name; 

This stores the ‘Jack’ string as a property of the object created.

@S.W.G. $this->name is saying grab the name property of this class. $name is saying use a variable called $name . So that’s why our __construct passes $name as a variable and sets $this->name = $name . We’re saying set the value of our name inside of this object equal to the value we passed in as $name .

The best way to learn about the $this variable in PHP is to try it against the interpreter in various contexts:

print isset($this); //true, $this exists print gettype($this); //Object, $this is an object print is_array($this); //false, $this isn't an array print get_object_vars($this); //true, $this's variables are an array print is_object($this); //true, $this is still an object print get_class($this); //YourProject\YourFile\YourClass print get_parent_class($this); //YourBundle\YourStuff\YourParentClass print gettype($this->container); //object print_r($this); //delicious data dump of $this print $this->yourvariable //access $this variable with -> 

So the $this pseudo-variable has the Current Object’s method’s and properties. Such a thing is useful because it lets you access all member variables and member methods inside the class. For example:

Class Dog< public $my_member_variable; //member variable function normal_method_inside_Dog() < //member method //Assign data to member variable from inside the member method $this->my_member_variable = "whatever"; //Get data from member variable from inside the member method. print $this->my_member_variable; > > 

$this is reference to a PHP Object that was created by the interpreter for you, that contains an array of variables.

Читайте также:  Генератор html css таблица

If you call $this inside a normal method in a normal class, $this returns the Object (the class) to which that method belongs.

It’s possible for $this to be undefined if the context has no parent Object.

Источник

Getting $this inside function

I have a function outside of my class, and i’m calling it from inside using call_user_func , my problem is that i cant access class inside the function. i need a way to access my class without passing it in arguments, if there was a way to make $this work inside the function that would be wonderful. Any advice other than passing class with argument into function will be appreciated;

function test($arg1) < $this->code = 10; // i know $this won't work here, // but i need a way to change $code // property from this function without // passing class into this function by using arguments > class MyClass < public $code; public function call() < call_user_func("test", "argument1"); >> 

Assuming you can’t pass in $this as an argument because you can’t modify that function, then why does that function need $this , and how would it use it? Otherwise, why not modify the function to pass in $this ? Some more details would help.

Why can’t you add an argument ? Can you move the function inside of the class ? What’s the purpose of this function ? If its purpose is to modify only one member of your class, can you pass it by reference as a function parameter instead ?

6 Answers 6

If you can move the function inside of your class, you would be able to call it like this:

call_user_func(array($this, 'the_function')); 

If you have PHP5.3, you can use a closure:

$that = $this; $function = function() use ($that) < // use $that instead of $this >; call_user_func($function); 

If you could add an argument, you could do this:

call_user_func('the_function', "argument1", $this); 

Pass $this as first parameter if the function asks for it:

(If the function has a parameter named $__this , pass $this as parameter)

function the_function($__this, $foo, $bar) < >$arguments = array('argument1'); $function = new ReflectionFunction('the_function'); $params = $function->getParameters(); if (count($params) > 0 && $params[0]->name == '__this') < array_unshift($arguments, $this); >$function->invokeArgs($arguments); 

You could do the same with doc comments:

/** * @IWantThis */ function the_function($__this) < >$function = new ReflectionFunction('the_function'); if (preg_match('/@IWantThis/', $function->getDocComment()) < . 

I don't understand who gave it or why but i upvoted you to counteract the down vote. this looks like a very helpful post.

Читайте также:  Регулярное выражение валидация email java

If I correctly understood your problem, the last solution I added may work; this allows your functions to declare that they want $this as first param.

@arn thank you for all of your useful solutions, the problem is most of my functions that will get called from my class have few overloads

Directly you have two options: Either passing the object to the function or the value to the object. I have no clue if that is the only job the function does, so this might not solve your problem, just showing the alternative as you wrote that passing the object to the function is not an option:

function test($arg1) < return 10; >class MyClass < public $code; public function call() < $this->code = call_user_func("test", "argument1"); > > 

If you don't want any of those, you must create some context both, the object and the function, operate in, to connect both with each other.

You can create context statically or dynamically. The first is often related to global variables which can result in hard to maintain code over time, an example:

function test($arg1) < global $object; $object->code = 10; > class MyClass < public $code; public function call() < global $object; $object = $this; call_user_func("test", "argument1"); unset($object); >> 

To create a more dynamical context, you are encapsulating everything into some context:

class contextCallback < private $object; public function __construct($object) < $this->object = $object; > public function test() < $this->object = 10; > > class MyClass < public $code; public function call() < $callback = new contextCallback($this); call_user_func(array($callback, 'test'), "argument1"); # or: $callback->test("argument1"); > > 

However I think then passing $this as an argument is much simpler and pretty much the same with far less code. I have no clue why you need call_user_func so it stays this abstract.

Edit: As another alternative and to decouple from concrete classes, when you only need to set values, consider returning multiple values:

function test($arg1) < $object->code = 10; return array($value, $object); > class MyClass < public $code; public function call() < list($value, $object) = call_user_func("test", "argument1"); foreach($object as $var =>$value) $this->$var = $value; > > 

Источник

Оцените статью