How to assign function reference for a function inside a class - php

Reference: Am using Slim Framework to develop Rest API application.
Problem: While doing so, used static functions. However, one of the functions that were called from my api code, threw an error "Using $this when not in object context". Since I cannot change the code being called which is generating the issue, I need to change my code.
Sample Code before change:
$app->post($mer_token_endpoint, get_token);
The rest of the code is fine, except the issue of $this. Wherever it is not called, those APIs work fine.
Now I changed the code to:
class Token {
public function get_token(Request $request, Response $response, array $args) {
.... code ....
}
}
$TokenObj = new Token();
$app->post($token_endpoint, $TokenObj->get_token);
How do I pass the reference of the function get_token declared in the class Token in the function post ?

Your code seems right but i want to know more about your code. Do you use static property in your function because if you have static class or function we use self instead of $this to access static property also without creating object

Related

PHP: How to change variable value to another class

I'm creating a class that uses google.
I want to return the value as an object from another class.
Example:
$x = new SocialServices($key, $keySecret, $apiKey);
Here I call the Google() method which requires a google.php file and creates the new object
$x->Google();
Here I want return Google class as $this.
public function Google() {
require 'PHP/google.php';
new Google($this->key, $this->secret, $this->apiKey, "#Google");
}
When i call
$x->YouTube();
It will be works.
I'm not sure I fully understood what you're asking, but I know for sure that you are missing a return in your method.
That means that the working method that returns a Google object would be
public function Google() {
require 'PHP/google.php';
return new Google($this->key, $this->secret, $this->apiKey, "#Google");
}
What I don't understand is what you mean by "Here I want return Google class as $this". I you want the method to return the same object to be able to concatenate, you can assign the Google object to an internal variable declared in the constructor and then just return $this right after the assignment.
By the way I would suggest you to avoid using the require, it's better if you use composer's autoloading.

PHP OOP MVC Fatal Error: Using $this when not in object context

So I've been looking all around, but nothing seems to be relevant to my problem.
I have an MVC, with some controllers and some tools like Session handling.
The session class consists of non-static methods, and in my controller I'm instantiating the session class like this:
public $sessions;
public function __construct () {
$this->sessions = new Session();
}
However, when I call it from a method in the controller, it returns the infamous "Using $this when not in object context". It doesn't make any sense to me.
public function index() {
$this->sessions->get('sessionToGet');
}
This will return the error.
Okay, I think it's a fault of how I wrote it. I came up with a better solution, which enabled me to switch to static calls instead on the session wrapper.
Fixed my problem, and now it atleast works very well.

Calling class method from other class (PHP)

I realize this is a common question and I have tried resolving it myself, but after following instructions from other answers I can't get it to work. So, this is the issue - I need to call a method from the class ClassOne in ClassTwo. So I did this:
class ClassOne{
public function methOne($par1,$par2){
mysql_query("insert into ps_loyalty_events (customer_id,event_id) values ('$par1','$par2') ") or die(mysql_error());
}
}
class ClassTwo{
private $customer; //initialize $customer in the constructor, to be defined as an instance of ClassOne() class and used as $this->customer
function __construct() {
$this->customer = new ClassOne();
}
public function methTwo(){
//some stuff here
$this->customer->methOne(6,10); //6,10 - randomly chosen parameters, irrelevant
//some more stuff here, this doesn't get executed at all
}
}
The priblem is not in ClassOne or the method methOne() because calling them directly from a regular PHP file in the following manner works:
$customer = new ClassOne();
$customer->methOne(6,10);
However, when I call it from the ClassTwo method, it does nothing - it just stops the execution of that function. Using try-catch doesn't seem to output anything. What am I doing wrong?
It's because your methTwo is static. When you call a static method of a class, that class is not instantiated into an object, and therefore it doesn't have the $this->customer property.
Unless there is a reason for the static method, you can change methoTwo:
public function methTwo(){
Edit: now that you have fixed that: what makes you think it isn't working? You don't do anything in methOne.
The code given is fine, see this Codepad demo of it working. That means there's some other code that we can't see that's causing the problem.
For simple solution, try to use extend classone in classtwo, so that all the method can user in classtwo by default
class class_two extends class_one
By above all the method of class one will be accessed into class two and can easily use that also. try it

Can php call non static method without instantiating the class first?

I register class methods for actions in my Wordpress plugin. When my method gets called by Wordpress, if I try to use the $this variable, php throws an error saying the call to $this variable is illegal outside the context of an object.
How can that be? I thought unless the method is static, you're not supposed to be able to call class methods if the class isn't instantiated! My method isn't static! What is happening?
The source code
Obviously the initialize is called from the main plugin file:
add_action('init', array('AffiliateMarketting', 'initialize'), 1);
My class looks like this:
class AffiliateMarketting
{
public function __construct()
{
// some initialization code
}
public function initialize()
{
add_action('woocommerce_before_single_product', array("AffiliateMarketting", "handleAffiliateReferral"));
}
public function handleAffiliateReferral($post)
{
$this->xxx(); // <---- offending function call
}
public function xxx()
{
}
}
The received error message is in fact Fatal error: Using $this when not in object context in <filename> on line <linenumber>.
You have to instantiate the class first. Something like this:
$affiliatemarketing = new AffiliateMarketing;
and then do the following:
add_action('init', array(&$affiliatemarketing, 'initialize'), 1);
Edit: forgot to add, your action in your method should be added like this:
add_action('woocommerce_before_single_product', array(&$this, "handleAffiliateReferral"));
You're not supposed to be. That's why you're getting an error.
I don't know exactly how you're registering the method (code would help), but probably, you're expecting Wordpress to take care of creating an instance, but that's not its role.
I found thought the Codex documented if the class name is specified using its string representation, then the add_action function will assume the call is to a static method.
On the other hand if and instance of the class is passed along then add_action will use that instance to make the method call.
Although Arman hasn't specified which php version he is using, I would assume it's probably 5.3.2 or 5.3.3. The error itself is rather similar to the one described in this question and the solution also would be to upgrade to the latest version of php 5.3.

PHP create_function Instance variable - Unable to call anonymous function: Follow up

This is somewhat a follow up to a previous question - but I've distilled the question down and have the "works" vs. "doesn't work" cases narrowed down much more precisely.
My Goal:
I have a class MyClass that has an instance variable myFunction. Upon creating a MyClass object (instantiating), the constructor assigns the instance variable myFunction with the result of a call to create_function (where the code and args come from a db call).
Once this object of type MyClass is created (and stored as an instance variable of another class elsewhere) I want to be able to call myFunction (the instance variable anonymous function) from "anywhere" that I have the MyClass object.
Experimental Cases -- below is my highly simplified test code to illustrate what works vs. what doesn't (i.e. when the expected functionality breaks)
class MyClass extends AnotherClass {
public $myFunction;
function __construct() {
$functionCode = 'echo "NyanNyanNyan";';
$this->myFunction();
/*Now the following code works as expected if put in here for testing*/
$anonFunc = $this->myFunction;
$anonFunc(); //This call works just fine (echos to page)!
/*And if i make this call, it works too! */
self::TestCallAnon();
}
public function TestCallAnon() {
$anonFunc2 = $this->myFunction;
$anonFunc2();
}
}
However, if I do the following (in another file, it errors saying undefined function () in... within the Apache error log.
//I'm using Yii framework, and this is getting the user
//objects instance variable 'myClass'.
$object = Yii::app()->user->myClass;
$object->TestCallAnon(); // **FAILS**
or
$func = $object->myFunction;
$func(); // ** ALSO FAILS **
In addition, several variations of calls to call_user_func and call_user_func_array don't work.
If anyone is able to offer any insight or help that would be great :).
Thanks in advance!
You can't pass references to functions around in PHP like you can in for instance JavaScript.
call_user_func has limited functionality. You can use it like so:
class MyClass {
function func() {}
static function func() {}
}
function myfunc() {}
$i = new MyClass();
call_user_func("myfunc", $args);
call_user_func(array($i, "func"), $args);
call_user_func(array(MyClass, "staticFunc"), $args);
I ended up solving this issue via a workaround that ended up being a better choice anyways.
In the end I ended up having a static class that had a method to randomly return one of the possible identifiers, and then another method which accepted that identifier to build the anonymous function upon each class.
Slightly less elegant than I would like but it ends up working well.
Thanks to everyone for your efforts.

Categories