Is there any ways to call non-static method within static method - php

I would like to call non-static method within static method. for example
Instead of calling method the following
$user = new User();
$userdata = $user->data($argument);
I would like to call as the following
$usedata = User::data($argument);
Firstly I build with the following setting
Class User{
public static function __callStatic($methodname, $argument) {
$objName = __CLASS__;
$obj = new $objName;
return $obj->find($argument);
}
public function find($argument) {
return $argument*2;
}
}
echo User::find(2);
But It show Warning message but code is successfully executed. Is there any other better solution for this scenario ? Sorry for any grammar mistake that I made since I am not native speaker and I am not very fluent with english.

If your find() method don't use the class context ($this), and that you need to call this method statically, then just declare it as static.

Related

error using $this in non-object context.intelephense(1030) and Non-static method cannot be called statically

I have a class with the structure below. And Im trying to call a method of the class with "$this->getTopProds($prodsInfo)" however Im getting an error:
"Cannot use '$this' in non-object context.intelephense(1030)"
And on the page the error is "Non-static method App\JsonResponse\Prod\ProdRender:: getTopProds() cannot be called statically".
Do you know what can be the issue?
class ProdRender
{
public static function hotel(array $prodsInfo): array
{
dd($this->getTopProds($prodsInfo));
}
private function getTopProds(array $prodsInfo)
{
//
}
}
No, we can't use this keyword inside a static method. “this” refers to the current instance of the class. But if we define a method as static, the class instance will not have access to it
To keep using the other method call inside the static method you need to change the second method getTopProds to be static too, and call it with self
self::getTopProds($prodsInfo)
In case you need it try this:
<?php
class ProdRender
{
public function hotel(array $prodsInfo)
{
return $this->getTopProds($prodsInfo);
}
private function getTopProds(array $prodsInfo)
{
return $prodsInfo;
}
}
$ho = new ProdRender();
$response = $ho->hotel(["fadf","ceec"]);
var_dump($response);

Why I get Non-static method should not be called statically?

I'm learning Laravel and the way I learn a new framework is going deep and found how/why magic happened in that.
So I learn facades and love them and wanna found how Laravel do the magic and found a way to have similar feature is __callStatic magic method. and here is my code :
class Facade {
public static function __callStatic($method,$args){
$instance = static::getFacade();
return call_user_func_array([$instance, $method], $args);
}
}
class DB extends Facade {
public static function getFacade(){
return new self();
}
public function init(){
echo 'INIT DB';
}
}
DB::init();
the code has a right output but I get this error:
Non-static method DB::init() should not be called statically :21
I don't understand why I got this and also Why I don't get this error in Laravel application that does this.
As init() is your public method and not static, you can call it via its object.
Try to call it by creating object of class DB.
$obj = new DB();
$obj->init();
Hope it will help you.
This method doen't have static keyword so you've to call it using the instance of that class and have to use this -> operator instead of ::
//this is a static method with static keyword preceding function
public static function getFacade(){
^^^^^^
return new self();
}
// this is non-static method with no static keyword
public function init(){
echo 'INIT DB';
}
Non-Static: create an instance and then call it using ->
$instance = new DB();
$instance->init();
Static: No need to create instance just call it using ::
DB::getFacade()
Because __callStatic method only catches inaccessible or non-exist methods so if you change
public function init(){
echo 'INIT DB';
}
To protected it will work
protected function init(){
echo 'INIT DB';
}
Also I asked a question before about this and I think it might be helpful for you
Here is my question

what does this mean in PHP ()->

I've seen this use of syntax a few times on the Yii framework. I tried searching for an explanation but got no examples. A link will be nice if possible. It goes something like class::model()->function();
My understanding is that model is an object of class therefore it can access the function. So I tried to code it but I get " Call to a member function sound() on a non-object in". Here's my code
class animal
{
private static $obj;
public static function obj($className = __CLASS__)
{
return self::$obj;
}
public static function walk()
{
return "walking";
}
}
include('animal.php');
class cat extends animal
{
public static function obj($className = __CLASS__)
{
return parent::obj($className);
}
public static function sound()
{
return "meow";
}
}
echo cat::obj()->sound();
Also what benefits does it have?
That is called an object operator and this, ->, calls a class method from your created object which is defined in that class.
Here is an explanation and some examples.
$obj = new Class; // Object of the class
$obj->classMethod(); // Calling a method from that class with the object
echo cat::obj()->sound();
This will display the output of the sound() method, called on the object that is returned from cat::obj().
The reason it's failing for you is because cat::obj() is not returning a valid object.
And the reason for that is because the obj() method returns the static obj property, but you're not actually setting that obj property anywhere.
The pattern you're trying to use here is known as a "Singleton" object. In this pattern, you call an obj() method to get the single instance of the class; every call to the method will give you the same object.
However the first call to the method needs to instantiate the object; this is what you're missing.
public static function obj($className = __CLASS__){
if(!static::$obj) {static::$obj = new static;}
return static::$obj;
}
See the new line where the object is created if it doesn't exist.
Also note that I've changed self to static. The way you're using this with class inheritance means that you probably expect to have a different static object for each class type, self will always return the root animal::$obj property, whereas static will return the $obj property for whichever class you're calling it from.
There are a few other bugs you need to watch out for too. For example, you've defined the sound() method as static, but you're calling it with ->, so it shouldn't be static.
Hope that helps.
The cat::obj() returns you a object of the type cat. With ->sound(); you're executing the function sound() from the class cat. All that should return "meow".
cat::obj() returns an object; ->sound(); execute a method of this object. Equivalent is
$o = cat::obj();
$o->sound();

Static and Non-Static Calling in PHP

ok I have this code, that I'm studying
class scope{
function printme(){
return "hello";
}
public static function printme(){
return "hello";
}
}
$s = new scope();
echo $s->printme(); //non-static call
echo "<br>";
echo scope::printme(); //static call
Now, this is not really the code of my project but these are the things I want to do
I want to create a class the will contain static and non-static functions.
I want a function to be available both on static and non-static calls.
As non-static function has a lot of operations on it, I also need to call it as a static function so that I will not need to instantiate the class. Is this possible? or I really needed to rewrite the function to another function or class?
NOTE: tell me if I'm doing some bad programming already.
Here is the rule:
A static method can be used in both static method and non-static method.
A non-static method can only be used in a non-static method.
If the instance of your class is rarely needed, you can have the static method create an instance, call the non-static method and return the value.
class Scope {
public function mynonstatic() {
}
public static function mystatic() {
$s = new Scope();
return $s->mynonstatic();
}
}
Remember that a static method is really just a global function with reduced scope. They are useful, but are should not be created without good reason.
As non-static function has a lot of operations on it, I also need to
call it as a static function so that I will not need to instantiate
the class. Is this possible? or I really needed to rewrite the
function to another function or class?
If you need it static, then make it static. If you need it not, then keep it the way it is. It is possible from within non-static function to call static function.
class Foo
{
public function bar()
{
Foo::zex();
// or self::zex() or even $this->zex();
}
public static function zex()
{
}
}
$foo = new Foo;
$foo->bar();
Ant the other way around.
class Foo
{
public function bar()
{
}
public static function zex()
{
$foo = new Foo;
$foo->bar();
}
}
When you should do it or should you do it at all is another question. The most common use of the latter is probably the Singleton pattern.

php static function

I have a question regarding static function in php.
let's assume that I have a class
class test {
public function sayHi() {
echo 'hi';
}
}
if I do test::sayHi(); it works without a problem.
class test {
public static function sayHi() {
echo 'hi';
}
}
test::sayHi(); works as well.
What are the differences between first class and second class?
What is special about a static function?
In the first class, sayHi() is actually an instance method which you are calling as a static method and you get away with it because sayHi() never refers to $this.
Static functions are associated with the class, not an instance of the class. As such, $this is not available from a static context ($this isn't pointing to any object).
Simply, static functions function independently of the class where they belong.
$this means, this is an object of this class. It does not apply to static functions.
class test {
public function sayHi($hi = "Hi") {
$this->hi = $hi;
return $this->hi;
}
}
class test1 {
public static function sayHi($hi) {
$hi = "Hi";
return $hi;
}
}
// Test
$mytest = new test();
print $mytest->sayHi('hello'); // returns 'hello'
print test1::sayHi('hello'); // returns 'Hi'
Entire difference is, you don't get $this supplied inside the static function. If you try to use $this, you'll get a Fatal error: Using $this when not in object context.
Well, okay, one other difference: an E_STRICT warning is generated by your first example.
Calling non-static methods statically generates an E_STRICT level warning.
In a nutshell, you don't have the object as $this in the second case, as
the static method is a function/method of the class not the object instance.
After trying examples (PHP 5.3.5), I found that in both cases of defining functions you can't use $this operator to work on class functions. So I couldn't find a difference in them yet. :(

Categories