Accessing a public/private function inside a static function? - php

Due to the fact that you can not use $this-> inside a static functio, how are you supposed to access regular functions inside a static?
private function hey()
{
return 'hello';
}
public final static function get()
{
return $this->hey();
}
This throws an error, because you can't use $this-> inside a static.
private function hey()
{
return 'hello';
}
public final static function get()
{
return self::hey();
}
This throws the following error:
Non-static method Vote::get() should not be called statically
How can you access regular methods inside a static method? In the same class*

Static methods can only invoke other static methods in a class. If you want to access a non-static member, then the method itself must be non-static.
Alternatively, you could pass in an object instance into the static method and access its members. As the static method is declared in the same class as the static members you're interested in, it should still work because of how visibility works in PHP
class Foo {
private function bar () {
return get_class ($this);
}
static public function baz (Foo $quux) {
return $quux -> bar ();
}
}
Do note though, that just because you can do this, it's questionable whether you should. This kind of code breaks good object-oriented programming practice.

You can either provide a reference to an instance to the static method:
class My {
protected myProtected() {
// do something
}
public myPublic() {
// do something
}
public static myStatic(My $obj) {
$obj->myProtected(); // can access protected/private members
$obj->myPublic();
}
}
$something = new My;
// A static method call:
My::myStatic($something);
// A member function call:
$something->myPublic();
As shown above, static methods can access private and protected members (properties and methods) on objects of the class they are a member of.
Alternatively you can use the singleton pattern (evaluate this option) if you only ever need one instance.

I solved this by creating an object of the concerning class inside a static method. This way i can expose some specific public functions as static function as well. Other public functions can only be used like $object->public_function();
A small code example:
class Person
{
public static function sayHi()
{
return (new Person())->saySomething("hi");
}
public function saySomething($text)
{
echo($text);
}
private function smile()
{
# dome some smile logic
}
}
This way you can only say hi if using the static function but you can also say other things when creating an object like $peter->saySomething('hi');.
Public functions can also use the private functions this way.
Note that i'm not sure if this is best practice but it works in my situation where i want to be able to generate a token without creating an object by hand each time.
I can for example simply issue or verify a token string like TokenManager::getTokenToken(); or TokenManager::verifyToken("TokenHere"); but i can also issue a token object like $manager = new TokenGenerator(); so i can use functionality as $manager->createToken();, $manager->updateToken(updateObjectHere); or $manager->storeToken();

Related

How can I access a property out of the static method?

Here is my code:
class {
$property = "something";
public static function myfunc() {
return $this->property;
}
}
but PHP throws this:
Using $this when not in object context
I know, the problem is using $this-> in a static method, ok I remove it like this:
class {
$property = "something";
public static function myfunc() {
return self::property;
}
}
But sadly PHP throws this:
Undefined class constant 'property'
How can I access a property which is out of a static method in it?
Generally, you should not do it. Static methods don't have an access to instance fields for a reason. You can do something like this, though:
// define a static variable
private static $instance;
// somewhere in the constructor probably
self::$instance = $this;
// somewhere in your static method
self::$instance->methodToCall();
Note that it will work only for a single instance of your class, since static variables are shared between all instances (if any).
You'll also need to add a bunch of validations (e.g. is $instance null?) and pay attention to all the implementation details that may cause you some troubles.
Anyway, I don't recommend this approach. Use it at your own risk.
Explaination
If you want to use a variable that wont change inside a class you don't want to instanciate, you need to use the static keyword in order to access it later in a method.
Also, you need a name for your class.
And finally, if you didn't specify a keyword as protected or public, you variable may be accessible outside the word, and so the method would be pointless. So I assume you need a protected value in order to use the method to call that variable.
Source-code
class Foo {
protected static $property = 'something';
public function getProperty() {
return self::$property;
}
}
echo Foo::getProperty(); /* will display : something */
echo Foo::$property; /* change from protected to public to use that syntax */
Documentation
PHP : classes.
PHP : static.
PHP : visibility.

Access static property through static and non-static methods?

I have a class and it has some static, some not static methods. It has a static property. I'm trying to access that property inside all of it's methods, I can't figure out the right syntax.
What I have is this:
class myClass {
static public $mode = 'write';
static public function getMode() {
return myClass::$mode;
}
public function getThisMode() {
return $this->mode;
}
}
Can anyone tell me the actual syntax for this one?
For static properties use the following even inside a non static function
return self::$mode;
The reason for this is because the static propery exists whether an object has been instantiated or not. Therefore we are just using that same pre-existing property.
If you are outside of the class, make sure not to forget the $ or you will see this error as well. For example, make sure to call it like this:
$myClass = new myClass();
echo $myClass::$mode;
Not like this:
echo $myClass::mode;

When to use static methods/fields in PHP?

When should I use Static functions/classes/fields in PHP? What are some practical uses of it?
you should not, it's rarely useful.
common usage for statics are factory methods and singleton::instance()
factory:
class Point{
private $x;
private $y;
public function __construct($x, $y){
...
}
static function fromArray($arr){
return new Point($arr["x"], $arr["y"]);
}
}
singleton:
class DB{
private $inst;
private function __construct(){
...
}
static function instance(){
if ($this->inst)
return $this->inst;
return $this->inst = new DB();
}
}
Usage of static methods in same in languages like Java/PHP.
One simple example can be that you want to use a variable across all instances of your class and any instance can change its value and you want it to get reflected in other instance as well.
class Foo{
static $count=0;
public function incrementCount(){
self::$count++;
}
public function getCount(){
return self:$count;
}
}
Without static you can't set count value via one object and access it in others.
I occasionally use STATIC Methods when I need simple functions in a Class that I also use outside the Class such as:
in a UserProfile class I have an method that returns an array that is used to pass data back to the class after the array is populated from the html page.
Class UserProfile{
Public Static get_empty_array(){
return array('firstname'=>'',lastname=>''); //usually much more complex multi-dim arrays
}
}
This way the empty array can be used within the class/object and outside as a starting template.
I also use Static Methods for functions that would normally be standalone functions but I want to keep them in the class so it is all together but also make them available outside as a static method such as:
public static convert_data($string){
//do some data conversion or manipulating here then
return $ret_value;
}
$converted_data = class::convert_data($string);
I do maintain an library of common user defined functions but I have found it handy to include some in the class to which it is closely related.

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

How to access a private member inside a static function in PHP

I have the following class in PHP
class MyClass
{
// How to declare MyMember here? It needs to be private
public static function MyFunction()
{
// How to access MyMember here?
}
}
I am totally confused about which syntax to use
$MyMember = 0; and echo $MyMember
or
private $MyMember = 0; and echo $MyMember
or
$this->MyMember = 0; and echo $this->MyMember
Can someone tell me how to do it?
I am kind of not strong in OOPS.
Can you do it in the first place?
If not, how should I declare the member so that I can access it inside static functions?
class MyClass
{
private static $MyMember = 99;
public static function MyFunction()
{
echo self::$MyMember;
}
}
MyClass::MyFunction();
see Visibility and Scope Resolution Operator (::) in the oop5 chapter of the php manual.
This is a super late response but it may help someone..
class MyClass
{
private $MyMember;
public static function MyFunction($class)
{
$class->MyMember = 0;
}
}
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..
class MyClass
{
private $MyMember;
private static $MyClasses;
public function __construct()
{
MyClass::$MyClasses[] = $this;
}
public static function MyFunction()
{
foreach(MyClass::$MyClasses as $class)
{
$class->MyMember = 0;
}
}
}
Within static methods, you can't call variable using $this because static methods are called outside an "instance context".
It is clearly stated in the PHP doc.
<?php
class MyClass
{
// A)
// private $MyMember = 0;
// B)
private static $MyMember = 0;
public static function MyFunction()
{
// using A) // Fatal error: Access to undeclared static property:
// MyClass::$MyMember
// echo MyClass::$MyMember;
// using A) // Fatal error: Using $this when not in object context
// echo $this->MyMember;
// using A) or B)
// echo $MyMember; // local scope
// correct, B)
echo MyClass::$MyMember;
}
}
$m = new MyClass;
echo $m->MyFunction();
// or better ...
MyClass::MyFunction();
?>
Static or non-static?
Did you ever asked yourself this question?
You can not access non static parameters / methods from inside
static method (at least not without using dependency injection)
You can however access static properties and methods from with in non-static method (with self::)
Properties
Does particular property value is assign to class blueprint or rather to it instance (created object from a class)?
If the value is not tight to class instance (class object) then you could declare it as as static property.
private static $objectCreatedCount; // this property is assign to class blueprint
private $objectId; // this property is assign explicitly to class instance
Methods
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.
And just because you don't need the $this keyword does not
automatically mean that you should make something static (though the
opposite is true: if you need $this, make it non-static).
Are you calling this method on one individual object or on the class in general? If you not sure which one to use because both are appropriate for particular use case, then always use non-static. It will give you more flexibility in future.
Good practice is to always start to design your class as non-static and force static if particular us case become very clear.
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.

Categories