Static method self php

Static method self php

For the ‘late static binding’ topic I published a code below, that demonstrates a trick for how to setting variable value in the late class, and print that in the parent (or the parent’s parent, etc.) class.

class cA
/**
* Test property for using direct default value
*/
protected static $item = ‘Foo’ ;

/**
* Test property for using indirect default value
*/
protected static $other = ‘cA’ ;

public static function method ()
print self :: $item . «\r\n» ; // It prints ‘Foo’ on everyway. 🙁
print self :: $other . «\r\n» ; // We just think that, this one prints ‘cA’ only, but. 🙂
>

public static function setOther ( $val )
self :: $other = $val ; // Set a value in this scope.
>
>

class cB extends cA
/**
* Test property with redefined default value
*/
protected static $item = ‘Bar’ ;

public static function setOther ( $val )
self :: $other = $val ;
>
>

class cC extends cA
/**
* Test property with redefined default value
*/
protected static $item = ‘Tango’ ;

public static function method ()
print self :: $item . «\r\n» ; // It prints ‘Foo’ on everyway. 🙁
print self :: $other . «\r\n» ; // We just think that, this one prints ‘cA’ only, but. 🙂
>

/**
* Now we drop redeclaring the setOther() method, use cA with ‘self::’ just for fun.
*/
>

class cD extends cA
/**
* Test property with redefined default value
*/
protected static $item = ‘Foxtrot’ ;

/**
* Now we drop redeclaring all methods to complete this issue.
*/
>

cB :: setOther ( ‘cB’ ); // It’s cB::method()!
cB :: method (); // It’s cA::method()!
cC :: setOther ( ‘cC’ ); // It’s cA::method()!
cC :: method (); // It’s cC::method()!
cD :: setOther ( ‘cD’ ); // It’s cA::method()!
cD :: method (); // It’s cA::method()!

Little static trick to go around php strict standards .
Function caller founds an object from which it was called, so that static method can alter it, replacement for $this in static function but without strict warnings 🙂

error_reporting ( E_ALL + E_STRICT );

function caller () $backtrace = debug_backtrace ();
$object = isset( $backtrace [ 0 ][ ‘object’ ]) ? $backtrace [ 0 ][ ‘object’ ] : null ;
$k = 1 ;

return isset( $backtrace [ $k ][ ‘object’ ]) ? $backtrace [ $k ][ ‘object’ ] : null ;
>

function set_data () b :: set ();
>

static function set () // $this->data = ‘Data from B !’;
// using this in static function throws a warning .
caller ()-> data = ‘Data from B !’ ;
>

$a = new a ();
$a -> set_data ();
echo $a -> data ;

You use ‘self’ to access this class, ‘parent’ — to access parent class, and what will you do to access a parent of the parent? Or to access the very root class of deep class hierarchy? The answer is to use classnames. That’ll work just like ‘parent’. Here’s an example to explain what I mean. Following code

class A
protected $x = ‘A’ ;
public function f ()
return ‘[‘ . $this -> x . ‘]’ ;
>
>

class B extends A
protected $x = ‘B’ ;
public function f ()
return ‘ x . ‘>’ ;
>
>

class C extends B
protected $x = ‘C’ ;
public function f ()
return ‘(‘ . $this -> x . ‘)’ . parent :: f (). B :: f (). A :: f ();
>
>

Читайте также:  Configuring php with apache2

$a = new A ();
$b = new B ();
$c = new C ();

Nice trick with scope resolution
class A
public function TestFunc ()
return $this -> test ;
>
>

public function __construct ()
$this -> test = «Nice trick» ;
>

public function GetTest ()
return A :: TestFunc ();
>
>

$b = new B ;
echo $b -> GetTest ();
?>

will output

This is a solution for those that still need to write code compatible with php 4 but would like to use the flexibility of static variables. PHP 4 does not support static variables within the class scope but it does support them within the scope of class methods. The following is a bit of a workaround to store data in static mode in php 4.

Note: This code also works in PHP 5.

The tricky part is when using when arrays you have to do a bit of fancy coding to get or set individual elements in the array. The example code below should show you the basics of it though.

class StaticSample
//Copyright Michael White (www.crestidg.com) 2007
//You may use and modify this code but please keep this short copyright notice in tact.
//If you modify the code you may comment the changes you make and append your own copyright
//notice to mine. This code is not to be redistributed individually for sale but please use it as part
//of your projects and applications — free or non-free.

//Static workaround for php4 — even works with arrays — the trick is accessing the arrays.
//I used the format s_varname for my methods that employ this workaround. That keeps it
//similar to working with actual variables as much as possible.
//The s_ prefix immediately identifies it as a static variable workaround method while
//I’m looking thorugh my code.
function & s_foo ( $value = null , $remove = null )
static $s_var ; //Declare the static variable. The name here doesn’t matter — only the name of the method matters.

if( $remove )
if( is_array ( $value ))
if( is_array ( $s_var ))
foreach( $value as $key => $data )
unset( $s_var [ $key ]);
>
>
>
else
//You can’t just use unset() here because the static state of the variable will bring back the value next time you call the method.
$s_var = null ;
unset( $s_var );
>
//Make sure that you don’t set the value over again.
$value = null ;
>
if( $value )
if( is_array ( $value ))
if( is_array ( $s_var ))
//$s_var = array_merge($s_var, $value); //Doesn’t overwrite values. This adds them — a property of the array_merge() function.
foreach( $value as $key => $data )
$s_var [ $key ] = $data ; //Overwrites values.
>
>
else
$s_var = $value ;
>
>
else
$s_var = $value ;
>
>

echo «Working with non-array values.
» ;
echo «Before Setting: » . StaticSample :: s_foo ();
echo «
» ;
echo «While Setting: » . StaticSample :: s_foo ( «VALUE HERE» );
echo «
» ;
echo «After Setting: » . StaticSample :: s_foo ();
echo «
» ;
echo «While Removing: » . StaticSample :: s_foo ( null , 1 );
echo «
» ;
echo «After Removing: » . StaticSample :: s_foo ();
echo «


» ;
echo «Working with array values
» ;
$array = array( 0 => «cat» , 1 => «dog» , 2 => «monkey» );
echo «Set an array value: » ;
print_r ( StaticSample :: s_foo ( $array ));
echo «
» ;

Читайте также:  Java изображение на кнопке

//Here you need to get all the values in the array then sort through or choose the one(s) you want.
$all_elements = StaticSample :: s_foo ();
$middle_element = $all_elements [ 1 ];
echo «The middle element: » . $middle_element ;
echo «
» ;

$changed_array = array( 1 => «big dog» , 3 => «bat» , «bird» => «flamingo» );
echo «Changing the value: » ;
print_r ( StaticSample :: s_foo ( $changed_array ));
echo «
» ;

//All you have to do here is create an array with the keys you want to erase in it.
//If you want to erase all keys then don’t pass any array to the method.
$element_to_erase = array( 3 => null );
echo «Erasing the fourth element: » ;
$elements_left = StaticSample :: s_foo ( $element_to_erase , 1 );
print_r ( $elements_left );
echo «
» ;
echo «Enjoy!» ;

  • Classes and Objects
    • Introduction
    • The Basics
    • Properties
    • Class Constants
    • Autoloading Classes
    • Constructors and Destructors
    • Visibility
    • Object Inheritance
    • Scope Resolution Operator (::)
    • Static Keyword
    • Class Abstraction
    • Object Interfaces
    • Traits
    • Anonymous classes
    • Overloading
    • Object Iteration
    • Magic Methods
    • Final Keyword
    • Object Cloning
    • Comparing Objects
    • Late Static Bindings
    • Objects and references
    • Object Serialization
    • Covariance and Contravariance
    • OOP Changelog

    Источник

    PHP Static Methods and Properties

    Summary: in this tutorial, you will learn about PHP static methods and static properties and understand the differences between the $this and self .

    Introduction to PHP static methods and properties

    So far, you have learned how to define a class that consists of methods and properties. To use the methods and properties of the class, you create an object and access these methods and properties via the object.

    Since these methods and properties are bound to an instance of the class, they are called instance methods and properties.

    PHP allows you to access the methods and properties in the context of a class rather than an object. Such methods and properties are class methods and properties.

    Class methods and class properties are called static methods and properties.

    Static methods

    To define a static method, you place the static keyword in front of the function keyword as follows:

      class MyClass < public static function staticMethod()  < >> Code language: HTML, XML (xml)

    Since a static method is bound to a class, not an individual instance of the class, you cannot access $this inside the method. However, you can access a special variable called self . The self variable means the current class.

    The following shows how to call a static method from the inside of the class:

    self::staticMethod(arguments);Code language: PHP (php)

    To call a static method from the outside of the class, you use the following syntax:

    className::staticMethod(arguments)Code language: JavaScript (javascript)
    MyClass::staticMethod()Code language: CSS (css)

    The following example defines the HttpRequest class that has a static method uri() that returns the URI of the current HTTP request:

    class HttpRequest < public static function uri(): string < return strtolower($_SERVER['REQUEST_URI']); > >Code language: PHP (php)

    The following calls the uri() static method of HttpRequest class:

    echo HttpRequest::uri();Code language: PHP (php)

    If the current HTTP request is https://www.phptutorial.net/php-static-method/ , the uri() method will return /php-static-method/ .

    Static properties

    To define a static property, you also use the static keyword:

    public static $staticProperty;Code language: PHP (php)
    class MyClass < public static $staticProperty; public static function staticMethod()  < >>Code language: PHP (php)

    To access a public static property outside of the class, you also use the class name with the :: operator:

    MyClass::$staticProperty;Code language: PHP (php)

    Like the static methods, to access static properties from within the class, you use the self instead of $this as follows:

    self::staticPropertyCode language: PHP (php)

    self vs. $this

    The following table illustrates the differences between the self and $this :

    $this self
    Represents an instance of the class or object Represents a class
    Always begin with a dollar ($) sign Never begin with a dollar( $ ) sign
    Is followed by the object operator ( -> ) Is followed by the :: operator
    The property name after the object operator ( -> ) does not have the dollar ($) sign, e.g., $this->property . The static property name after the :: operator always has the dollar ( $ ) sign.

    PHP static methods and properties example

    Suppose that you want to create an App class for your web application. And the App class should have one and only one instance during the lifecycle of the application. In other words, the App should be a singleton.

    The following illustrates how to define the App class by using the static methods and properties:

     class App < private static $app = null; private function __construct()  < >public static function get() : App < if (!self::$app) < self::$app = new App(); > return self::$app; > public function bootstrap(): void < echo 'App is bootstrapping. '; > >Code language: HTML, XML (xml)

    First, define a static property called $app and initialize its value to null :

    private static $app = null;Code language: PHP (php)

    Second, make the constructor private so that the class cannot be instantiated from the outside:

    private function __construct()  Code language: PHP (php)

    Third, define a static method called get() that returns an instance of the App class:

    public static function get() : App < if (!self::$app) < self::$app = new App(); > return self::$app; >Code language: PHP (php)

    The get() method creates an instance of the App if it has not been created, otherwise, it just simply returns the App’s instance. Notice that the get() method uses the self to access the $app static property.

    Fourth, the bootstrap() method is just for demonstration purposes. In practice, you can place the code that bootstraps the application in this method.

    The following shows how to use the App class:

     $app = App::get(); $app->bootstrap();Code language: HTML, XML (xml)

    In this code, we called the get() static method from the App class and invoked the bootstrap() method of the App ‘s instance.

    Summary

    • Static methods and properties are bound to a class, not individual objects of the class.
    • Use the static keyword to define static methods and properties.
    • Use the self keyword to access static methods and properties within the class.

    Источник

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