Php accessing static property as non static

PHP reference Class from variable with static method access

You could try to declare your parameters as static. just so you can access it from static method but that usually is not what you want to do. So if you really need to access $this from static method then it means that you need to rethink/redesign your class architecture because you have don it wrong. ,That works. You can access the private member that way, but if you had $class you should just make MyFunction a method of the class, as you would just call $class->MyFunction(). However you could have a static array that each instance is added to in the class constructor which this static function could access and iterate through, updating all the instances. ie. When deciding on making a method static or non-static you need to ask yourself a simple question. Does this method need to use $this? If it does, then it should not be declared as static.,Within static methods, you can’t call variable using $this because static methods are called outside an «instance context».

class MyClass < private static $MyMember = 99; public static function MyFunction() < echo self::$MyMember; >> MyClass::MyFunction(); 

Answer by Preston Robbins

Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside methods declared as static. , Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. These can also be accessed statically within an instantiated class object. , Calling non-static methods statically throws an Error. , Static properties are accessed using the Scope Resolution Operator (::) and cannot be accessed through the object operator (->).

foo foo Notice: Accessing static property Foo::$my_static as non static in /in/V0Rvv on line 23 Warning: Undefined property: Foo::$my_static in /in/V0Rvv on line 23 foo foo foo foo 

Answer by Allen Shaw

When to use static vs instantiated classes in PHP?,Example: This example illustrates the static method in PHP.,Below is the PHP code which shows the use of static methods.,How to get the MAC and IP address of a connected client in PHP?

Читайте также:  Android connect mysql java

In certain cases, it is very handy to access methods and properties in terms of a class rather than an object. This can be done with the help of static keyword. Any method declared as static is accessible without the creation of an object. Static functions are associated with the class, not an instance of the class. They are permitted to access only static methods and static variables. To add a static method to the class, static keyword is used.

public static function test() < // Method implementation >

They can be invoked directly outside the class by using scope resolution operator (::) as follows:

The next value is: 1 The next value is: 2 The next value is: 3 The next value is: 4 The next value is: 5 
This is non-static This is static 

Answer by Guadalupe Jones

A class can have both static and non-static methods. A static method can be accessed from a method in the same class using the self keyword and double colon (::):,To access a static method use the class name, double colon (::), and the method name:,To call a static method from a child class, use the parent keyword inside the child class. Here, the static method can be public or protected.,Static methods can also be called from methods in other classes. To do this, the static method should be public:

Static methods can be called directly — without creating an instance of the class first.

Static methods are declared with the static keyword:

Answer by Emelia Nicholson

NOTE: If there is any static member function or variable in the class, we cannot refer it using the $this.,Whenever we want to call any variable of class from inside a member function, we use $this to point to the current object which holds the variable.,We can also use $this to call one member function of a class inside another member function.,this keyword is used inside a class, generally withing the member functions to access non-static members of a class(variables or functions) for the current object.

Let’s take an example to understand the usage of $this .

name = $name; > // public function to get value of name (getter method) public function getName() < return $this->name; > > // creating class object $john = new Person(); // calling the public function to set fname $john->setName("John Wick"); // getting the value of the name variable echo "My name is " . $john->getName(); ?>

Instead of $this , for static class members(variables or functions), we use self , along with scope resolution operator :: . Let’s take an example,

Let’s take a code example to understand this better:

name; > // public function to get job description public function getDesc() < return $this->desc; > // static function to get the company name public static function getCompany() < return self::$company; >// non-static function to get the company name public function getCompany_nonStatic() < return self::getCompany(); >> $objJob = new Job(); // setting values to non-static variables $objJob->name = "Data Scientist"; $objJob->desc = "You must know Data Science"; /* setting value for static variable. done using the class name */ Job::$company = "Studytonight"; // calling the methods echo "Job Name: " .$objJob->getName()."
"; echo "Job Description: " .$objJob->getDesc()."
"; echo "Company Name: " .Job::getCompany_nonStatic(); ?>

Answer by Ariyah Hickman

A static method can be accessed directly by the class name and doesn’t need any object, A static variable can be accessed directly by the class name and doesn’t need any object,Following diagram shows, how reference variables & objects are created and static variables are accessed by the different instances., A single copy to be shared by all instances of the class

Step 1) Copy the following code into a editor

public class Demo < public static void main(String args[])< Student s1 = new Student(); s1.showData(); Student s2 = new Student(); s2.showData(); //Student.b++; //s1.showData(); >> class Student < int a; //initialized to zero static int b; //initialized to zero only when class is loaded not for each object created. Student()< //Constructor incrementing static variable b b++; >public void showData() < System.out.println("Value of a = "+a); System.out.println("Value of b = "+b); >//public static void increment() < //a++; //>>

Step 4) It is possible to access a static variable from outside the class using the syntax ClassName.Variable_Name. Uncomment line # 7 & 8 . Save , Compile & Run . Observe the output.

Value of a = 0 Value of b = 1 Value of a = 0 Value of b = 2 Value of a = 0 Value of b = 3 

Step 5) Uncomment line 25,26 & 27 . Save , Compile & Run.

 error: non-static variable a cannot be referenced from a static context a++; 

Example: How to access static block

public class Demo < static int a; static int b; static < a = 10; b = 20; >public static void main(String args[]) < System.out.println("Value of a = " + a); System.out.println("Value of b = " + b); >>

you will get following output of the program.

Value of a = 10 Value of b = 20 

Answer by Jolie Avila

The static keyword defines a static method or property for a class, or a class static initialization block (see the link for more information about this usage). Neither static methods nor static properties can be called on instances of the class. Instead, they’re called on the class itself. ,In order to call a static method or property within another static method of the same class, you can use the this keyword., Classes Class static initialization blocksconstructorextendsPrivate class featuresPublic class fieldsstatic ,Static methods are often utility functions, such as functions to create or clone objects, whereas static properties are useful for caches, fixed-configuration, or any other data you don’t need to be replicated across instances.

static methodName() < . >static propertyName [= value]; // Class static initialization block static

Источник

PHP RFC: Reclassify E_STRICT notices

This RFC proposes to reclassify the few existing E_STRICT notices and remove this error category.

This is accomplished by doing one of the following:

The motivation behind this change is to simplify our error model and resolve the currently unclear role of strict standards notices.

Proposal

The following section lists all strict standards notices currently in use (with code sample and error message) as well as the proposed resolution and the reasoning behind it.

The E_STRICT constant will be retained for better compatibility, it will simply no longer have meaning in PHP 7.

Indexing by a resource

$file = fopen(__FILE__, 'r'); $array[$file] = true; // Resource ID#3 used as offset, casting to integer (3)

Proposed resolution: Convert to E_NOTICE .

Reason: E_NOTICE is also used for array to string and object to int/float conversions.

Abstract static methods

abstract class Foo { abstract static function bar(); } // Static function Foo::bar() should not be abstract

Proposed resolution: Remove notice.

Reason: We currently allow the use of abstract static functions in interfaces, as such it is inconsistent to not allow them as abstract methods. By using late static binding a method in the abstract class can reasonably depend on the existence of a static method in a superclass. (As far as any usage of LSB can be considered reasonable).

«Redefining» a constructor

Update: This notice is already removed by the deprecation of PHP 4 constructors — this section is no longer relevant, just keeping it here for the overview.

class Foo { function foo() {} function __construct() {} } // Redefining already defined constructor for class Foo

Proposed resolution: Remove notice.

Reason: If a PHP 5 constructor exists, the PHP 4 constructor will be a normal method, as such the notice is somewhat bogus. It is also order dependent, i.e. it will not be thrown if the order of foo and __construct is swapped.

Signature mismatch during inheritance

class Foo { public function method() {} } class Bar extends Foo { public function method($arg) {} } // Declaration of Bar::method() should be compatible with Foo::method()

Proposed resolution: Convert to E_WARNING .

Reason: If the same signature mismatch occurs when implementing an interface or an abstract function a fatal error is thrown instead of a strict standards notice. A signature mismatch is a significant issue, which will likely prevent the use of the child object in place of the parent object.

Same (compatible) property in two used traits

trait A { public $prop; } trait B { public $prop; } class C { use A, B; } // A and B define the same property ($prop) in the composition of C. // This might be incompatible, to improve maintainability consider // using accessor methods in traits instead.

Proposed resolution: Remove notice.

Reason: This appears to be a purely informational notice about coding style.

Accessing static property non-statically

class Foo { public static $prop = 24; } $obj = new Foo; $obj->prop = 42; // Accessing static property Foo::$prop as non static

Proposed resolution: Convert to E_NOTICE

Reason: E_NOTICE is used for a number of other property related noticed, like indirect modification or undefined properties. Accessing a static property non-statically makes it look like the property is only changed on the object, which is not true.

Only variables should be assigned by reference

$a =& substr("foo", 1); // Only variables should be assigned by reference

Proposed resolution: Convert to E_NOTICE

Reason: E_NOTICE is used when you try to return the result of a by-value function call by-reference, which is a conceptually similar situation.

Only variables should be passed by reference

function by_ref(&$ref) {} by_ref(substr("foo", 1)); // Only variables should be passed by reference

Proposed resolution: Convert to E_NOTICE

Reason: E_NOTICE is used when you try to return the result of a by-value function call by-reference, which is a conceptually similar situation.

Calling non-static methods statically

class Foo { public function method() {} } Foo::method(); // Non-static method Foo::method() should not be called statically

Proposed resolution: Convert to E_DEPRECATED

Reason: This is already deprecated if the call occurs from an instance method. Not annotating methods as static is an obsolete PHP4-ism.

Backward Incompatible Changes

Some of the strict standards notices are converted to an error category that is considered more severe. As such error handlers might treat it more severely, resulting in BC breakage.

The E_STRICT constant will be retained, as such existing error_reporting(E_ALL|E_STRICT) calls will continue to work fine.

Vote

Requires a 2/3 majority, as it is a language change. Voting started on 2015-03-15 and ended on 2015-03-25.

Источник

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