PHP Classes calling functions to it - php

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();

Related

Calling a Wordpress function out of class

I have a woocommerce plugin that has a class Foo:
function wc_foo_init(){
class WC_Foo extends WC_Shipping_Method{
$var=get_option(); //gets an option for this session
function sayHello(){
echo $var;
}
new WC_Foo();
}
I want to call sayHello() out of the Foo class:
function bar(){
WC_Foo->sayHello();
}
But I get this error:
Fatal error: Call to a member function `sayHello` on a non-object.
You must instantiate class before make call of its methods:
$foo = new WC_Foo();
$foo->sayHello();
or if your php version is greater than 5.4 you can do:
(new WC_Foo())->sayHello();
Use $this selector if you are calling the method within the class
function bar(){
$this->sayHello();
}
If you want to call the method from other place,
you need to instantiate the class like this:
$object = new WC_Foo();
$object->sayHello();
Or make the method static like this:
public static function sayHello(){
echo "Hello";
}
And call it like this:
WC_Foo::sayHello();
// this way you dont need $object = new WC_Foo();
This might not be the full code, so it's pretty weird what you have there, but let's go.
Since you have a function to init your object, you would probably want to at least return that instance. This code might help you understand:
function init_foo(){
class foo{
function say(){
echo 'hello';
}
}
$foo1 = new Foo();
return $foo1;
}
function bar($foo3){
$foo3->say();
}
$foo2 = init_foo();
bar($foo2);
So, first we create the object and return it. Then we inject it in the bar function, just needing to call the method after that. (I used different var names so it's easier to understand scope)

Calling Class Method in PHP

When to call class method directly?
<?php
Class::method();
?>
When to call class method after object instatiated?
<?php
$object = new Class();
$object->method();
?>
What are the differences between both of them?
Methods which are defined as static those methods will be called directly.
Like function1 is static so it will be called as
A::function1();
class A
{
public static function function1()
{
$a = "Hi";
return $a;
}
public function function2()
{
$a = "Hi";
return $a;
}
}
Where as second method is not static and it will be called on the object of class A like below
$object = new A();
$object->function2();
:: scope resolution operator that is used for direct call static class methods without object
Class::method();
you can use class variables $this->... in this method.
$object = new Class(); new is create object of class and you can also use class variables from object
in simple way object is instance of class.
if you are making any class function static then you can access by using scope resolution operator like in 1st case.In case of static function $this is not available inside function.
<?php
class Product
{
public static function method() //static function
{
echo "static function" ;
}
}
Product::method(); // we can make direct call
?>
while in 2nd case object is created and we are accessing class methods through objects.
$object = new Class();
$object->method();

What is meant by static invocation in definition of call_user_func

I have problems to understand the PHP manual for call_user_func, especially the parameter description:
The function to be called. Class methods may also be invoked statically using this function by passing array($classname, $methodname) to this parameter.
Example: Using a class method
<?php
class myclass {
function say_hello()
{
echo "Hello!\n";
}
}
$classname = "myclass";
call_user_func(array($classname, 'say_hello'));
?>
Also kindly explain this code line "call_user_func(array($classname, 'say_hello'))". Of course array($classname, 'say_hello') is not a method name.
Passing an array to call_user_func is a special case for invoking class methods, static and non-static. In the example you gave, you could do this:
<?php
class myclass {
public function say_hello()
{
echo "Hello!\n";
}
public static function say_hello_static() {
echo "Hello static!\n";
}
}
//Call static method
call_user_func(array('myclass','say_hello_static'));
//Call object method
$myobject = new myclass();
call_user_func(array($myobject,'say_hello'));
?>
As of PHP 5.2.3 you can call static methods by using a string, instead of an array, e.g:
call_user_func('myclass::say_hello_static');

Instantiating classes and accessing methods from different classes

I'm trying to use a Class_B function in one of Class_A's functions. But a lot of Class_B's functions include $this which causes problems. These are both classes (each class is of course in its own file):
class Class_A
{
function hello()
{
require('class_b.php');
echo 'Hello ' . Class_B::person();
}
function bye()
{
require('class_b.php');
echo 'Bye ' . Class_B::person();
}
}
class Class_B
{
function person()
{
// various operations and variables
echo $this->get_user($id);
}
}
When I run the Class_A file I get Call to undefined method Class_A::person() in (...) because I think the $this value is changed when I instantiate the Class_A class. It overrules the Class_B value. How can I stop this?
Also, another question: how can I access Class_B from every function in Class_A? I don't want to redeclare the class. Do I need to do this:
class Class_A
{
function function1()
{
require('class_b.php');
$class_b = new Class_B();
// code
}
function function2()
{
require('class_b.php');
$class_b = new Class_B();
// code
}
}
Or do I need to use a constructor or something?
By Class_B::person() you are calling the method statically. So you should declare the person() method as static and can't use $this because you don't have an instance of Class_B.
If you need an instance of Class_B, just create it and store in the class_B on construction.
class Class_A {
private $b;
function __construct()
{
$this->b = new Class_B();
}
function stuff()
{
$this->b->person();
}
Don't put require inside a method. Code in an included file inherits the scope of the place where you include it, and in your example, bad things happen. Also, for class definition scripts, consider require_once instead of require, to avoid multiple definitions.
As a rule of thumb, put all includes and requires at the top of your script. Better yet, set up a class autoloader, and register it in an auto_prepend script. That way, you won't have to manually include anything at all (at least not for class definitions).
What you might want is dependency injection, whereby you pass an object of Class_B into Class_A's constructor and hold it as a property in Class_A. It then becomes available in Class_A as $this->classB or similar.
// Include Class_B code outside the class.
require_once('class_b.php');
class Class_A {
// Property to hold Class_B
public $b;
// Constructor
public function __construct($b) {
$this->b = $b;
}
public function function1(){
// code
$this->b;
}
public function function2(){
// code
$this->b;
}
}
// Now call your objects:
// The Class_B which will be injected into A
$b = new Class_B();
// Your Class_A, which holds an instance of Class_B as a property
$a = new A($b);

call a static method inside a class?

how do i call a static method from another method inside the same class?
$this->staticMethod();
or
$this::staticMethod();
self::staticMethod();
More information about the Static keyword.
Let's assume this is your class:
class Test
{
private $baz = 1;
public function foo() { ... }
public function bar()
{
printf("baz = %d\n", $this->baz);
}
public static function staticMethod() { echo "static method\n"; }
}
From within the foo() method, let's look at the different options:
$this->staticMethod();
So that calls staticMethod() as an instance method, right? It does not. This is because the method is declared as public static the interpreter will call it as a static method, so it will work as expected. It could be argued that doing so makes it less obvious from the code that a static method call is taking place.
$this::staticMethod();
Since PHP 5.3 you can use $var::method() to mean <class-of-$var>::; this is quite convenient, though the above use-case is still quite unconventional. So that brings us to the most common way of calling a static method:
self::staticMethod();
Now, before you start thinking that the :: is the static call operator, let me give you another example:
self::bar();
This will print baz = 1, which means that $this->bar() and self::bar() do exactly the same thing; that's because :: is just a scope resolution operator. It's there to make parent::, self:: and static:: work and give you access to static variables; how a method is called depends on its signature and how the caller was called.
To see all of this in action, see this 3v4l.org output.
This is a very late response, but adds some detail on the previous answers
When it comes to calling static methods in PHP from another static method on the same class, it is important to differentiate between self and the class name.
Take for instance this code:
class static_test_class {
public static function test() {
echo "Original class\n";
}
public static function run($use_self) {
if($use_self) {
self::test();
} else {
$class = get_called_class();
$class::test();
}
}
}
class extended_static_test_class extends static_test_class {
public static function test() {
echo "Extended class\n";
}
}
extended_static_test_class::run(true);
extended_static_test_class::run(false);
The output of this code is:
Original class
Extended class
This is because self refers to the class the code is in, rather than the class of the code it is being called from.
If you want to use a method defined on a class which inherits the original class, you need to use something like:
$class = get_called_class();
$class::function_name();
In the later PHP version self::staticMethod(); also will not work. It will throw the strict standard error.
In this case, we can create object of same class and call by object
here is the example
class Foo {
public function fun1() {
echo 'non-static';
}
public static function fun2() {
echo (new self)->fun1();
}
}
call a static method inside a class
className::staticFunctionName
example
ClassName::staticMethod();

Categories