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();
Related
class A {
public function f(){
$this->ar[0] = 'something';
}
}
For example, how can function f be called such that $this->ar will refer to an array declared outside of class A? Assume that A is not inheriting ar.
Edit:
I tried to simplify the question. The actual code I'm looking at is
the function index in opencart's ControllerStartupStartup class
The function index is using $this to access class instances that aren't defined in that class: $this->db,$this->config, and $this->tax.
They are not declared in the parent class Controller either.
The function is being called with call_user_func_array(array($controller, $this->method), $args); in the Action class.
Maybe you can make "ar" known and provide it in the class as setter, so the instance ar is known and you can address it with $this
class A {
$ar = array();
public function f(){
$this->ar[0] = 'something';
}
}
// INSTANCE with Setter
$ar[0]='whatever';
$class = new A();
$class->ar = &$ar;
$class->f();
echo $ar[0];
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::
What is the basic difference between calling a method using -> and ::
class a
{
function b()
{
echo "abc";
}
}
What is the difference between these two?
a::b();
$c = new a; $c->b();
-> executes the method in the context of an instance, while :: accesses the method in static context of a class. The latter only has access to static members of the class via self::, while the former can also use the instance members via $this->.
When defining your class, you should be explicitly declare the visibility of your properties and methods, and whether or not they are static.
The class in your example should be:
class A
{
public static function b() {
echo "abc";
}
}
The method b() should be static because it doesn't refer to any instance variables. To call b() you would use:
A::b();
If your method was to use an instance variable (a non-static property) your class would probably look like this:
class Foo
{
private $bar; // non static instance variable
public function __construct($bar) {
$this->bar = $bar; // instance variable set in the constructor
}
public function baz() {
echo $this->bar; // instance variable referred to in the non-static method
}
}
Then you would call the function like this:
$x = new Foo('abc');
$x->baz();
a::b();
The above statement used to call static method in the context of class(independent of any object cotext) thus $this is not available in static method
$c = new a; $c->b();
The above satement used to call instance method in the context of object($c) thus $this(refer to object $c) is available inside instance method
Thanks
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();
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);