Call Function From One Function To Another In A Class PHP - php

I would like to use a function from inside my class in another function. I have tried just calling it but it does not seem to work. Here is what I am doing:
class dog {
public function info($param) {
//Do stuff here
}
public function call($param2) {
//Call the info function here
info($param2);
//That does not seem to work though, it says info is undefined.
}
}
So basically my question is how do I call a function from another in a class. Thank You, I am VERY new to classes! :D

In PHP you always need to use $this-> to call a class method (or any attribute). In your case the code is:
public function call($param2) {
//Call the info function here
$this->info($param2);
//That does not seem to work though, it says info is undefined.
}
Please note that If you declare your method as static, then you will have to use either self:: or static::.
This is a basic PHP OOP syntax, for more information read the doc

Related

PHP call class variable / property with stored closure

So I am making a Magento module in PHP. I want my logging to be consistent across all classes. My idea was to define a method in the helper class and call it. However being the pre-optimizer that I am, I figure making multiple calls to a class via the Mage::Helper() method to be more expensive than it needs to be, especially since most of my logging in singleton models anyways. So my now my idea is to use closures, define my method in the helper, make one call to the helper and register the method in a class variable.
class Comp_Mod_Helper_Data extends Mage_Core_Helper_Abstract {
public function getLogger() {
return function ($obj, $type= Zend_Log::DEBUG) {
Mage::log($obj, $logType, 'comp-mod.log', true);
};
}
}
Use:
class Comp_Mod__IndexController extends age_Core_Controller_Front_Action {
private $_log;
protected function _construct() {
$this->_log = Mage::Helper('mod')->getLogger();
}
}
However while it works ... it is not great to use. I'm either stuck doing:
$log = $this->_log;
$log('hello world');
// one awkward liner
($this->_log)('hello world');
While neat that it works is not readable nor standard, i.e. confusing!. The error that it get when using $this->_log('hello world'); is that the method does not exist. I assume because PHP is looking for a method call when using the syntax $this->method();
I do understand that A) I could just suck it up and use Mage::Helper everywhere, and B) that I could store the helper object in a variable and call like $this->helper->log(), and C) that static variables work, see PHP closure as static class variable
So, is there a way to get a non-static class variable to call the closure instead of looking for a non-existing method?
You could make use of the __call magic method:
class Comp_Mod__IndexController extends age_Core_Controller_Front_Action {
public function __call($method, array $args)
{
switch ($method)
{
case '_log':
return call_user_func_array(Mage::Helper('mod')->getLogger(), $args);
}
return null;
}
}
Then use it like you wanted to:
$this->_log('string to log');

How to Access $this variable inside nested functions in codeigniter?

I have a controller for Nu soap WSDL Like:
class webservice extends CI_Controller
{
function index()
{
$this->load->library('encrypt');
$this->load->model('MWSDl');
//...
function buy($apicode)
{
if(!$this->MWSDl->check_gateway($apicode)) //Error occurred php Cannot find "$this" Variable
}
//...
$this->nusoap_server->service(file_get_contents("php://input"));
}
}
How to Access $this inside buy function?
I tried by global $this But Error occurred!
Error:
Fatal error: Using $this when not in object context in \controllers\webservice.php on line 9
You are going wrong about the whole concept. PHP is not Javascript.You shouldn't nest functions, specially not when using OOP frameworks. If you run function index twice, the second time you will probably get an error that function buy is already declared since first run of index will declare function buy.
I would declare them as class member functions / methods.
class Webservice extends CI_Controller {
function __construct()
{
parent::construct();
$this->load->library('encrypt');
$this->load->model('MWSDl');
}
function index()
{
// do something like
$apicode = 'xxxxxx';
$this->buy($apicode);
//or what ever else you need to do
}
function buy($apicode)
{
if(!$this->MWSDl->check_gateway($apicode)) {
$this->nusoap_server->service(file_get_contents("php://input"));
}
}
}
No need to use globals in codeigniter.
Let me know if this helps.
I understand your question. I also had the same problem with nusoap. When registering a service you have to make a function. Thus in CI you are creating it inside a class function which makes the service function is nested inside, and cannot be taken outside.
Why don't you try this below? I use it all the time before, with helper etc. It's simple and I have tried it and it works.
Put this inside your nested function:
$ci =& get_instance();
and the rest you have to replace $this with $ci
eq. $ci->some_model->some_function(); or $ci->some_var = 'something';
And it also work if you tried to call a db.
I hope this will help you.

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

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.

How to use a doctrine construct function

Doctrine documentation says you can use
public function construct() { ... }
as a construct function since __construct can't be overridden.
When I place it in my code and put a echo in it
public function construct() { echo "constructing..."; }
it isn't called during the construction of the object.
How is it supposed to be called or is there some fancy way of calling a function during (or just after) load time in PHP?
Just because there is no output it doesn't mean that the method is not called. Try a exit('constructing...'); instead.
By the way: Works fine here with Doctrine 1.1 :-)

Categories