How to call a method of a class? - php

I got 2x public functions in a class that must call 1 private function with different parameters also in the same class... for some reason it tell me that it can't find the function...
example:
class Foo {
private function Do(...)
{
....
return $whatever;
}
public function One(...)
{
return Do(...);
}
public function Two(...)
{
return Do(...);
}
}
am getting error:
Fatal error: Call to undefined function do() in ...

You have to use $this to refer to the instance and the T_OBJECT_OPERATOR to access/mutate/call members/methods of an instance, e.g.
$this->do();
Please go through the
Chapter on Classes and Objects in the PHP Manual and
What is the point of having $this and self:: in PHP?

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

How to Invoke Object that's a Public Property

Take the following example of two classes:
class Yolo {
public function __invoke() {
echo 'YOLO';
}
}
class Swag {
public $yolo;
public function __construct() {
$this->yolo = new Yolo();
}
}
Is it possible to invoke the Yolo object via an instance of Swag?
(new Swag())->yolo(); throws a warning and doesn't call __invoke:
PHP Warning: Uncaught Error: Call to undefined method Swag::yolo()
In PHP 7 you can directly call it (just need extra braces):
((new Swag())->yolo)();
In PHP 5 you need a temp variable:
$y=(new Swag())->yolo;
$y();
The problem is that you try to call the function yolo() on the Swag class. In your case you have to use the public class variable and call the subclass over that.
var_dump((new Swag())->yolo);
that is your object. When you use () you try to call the class not the class variable.
You do not even have to make it a public method.
But you might have to reroute the call manually since the callable method is created at runtime:
class Yolo {
public function __invoke() {
echo 'YOLO';
}
}
class Swag {
private $yolo;
public function __construct() {
$this->yolo = new Yolo();
}
function __call($method, $args) {
if(is_callable($this->$method))
{
return call_user_func_array($this->$method, $args);
}
}
}
(new Swag())->yolo();
It would probably a good idea to check first, if the called method exists and if it is actually callable.
But the example works as a proof of concept.

How to call the method of an anonymous class when the anonymous class is passed as a parameter to the class method of a normal class?

I'm using PHP 7.1.11
I've tried following code for an Anonymous Class which is declared as a parameter to a class method. I want to call the method present in an anonymous class. But I'm getting a fatal error. How should I call the anonymous class method successfully?
<?php
class Util {
private $logger;
public function __construct(){}
public function getLogger($logger) {
$this->logger = $logger;
}
public function setLogger($logger) {
$this->logger = $logger;
}
}
$util = new Util();
$util->setLogger(new class {
public function log($msg) {
echo $msg;
}
});
$util->setLogger()->log('Phil runs very fast'); // Ioutput should be : Phil runs very fast
?>
Output I'm currently getting :
Fatal error: Uncaught ArgumentCountError: Too few arguments to function Util::setLogger(), 0 passed in anonymous_class_ex.php on line 27 and exactly 1 expected in anonymous_class_ex.php:13 Stack trace: #0 anonymous_class_ex.php(https://stackoverflow.com/posts/47605127/edit27): Util->setLogger() #1 {main} thrown in anonymous_class_ex.php on line 13
You'd run it like you would any dynamic reference to a callable, as a two-element array: [object, 'methodName']. Here the object is your anonymous class definition:
$util->setLogger([new class {
public function log($msg) {
echo $msg;
}
}, 'log']);
Here's a stand-alone runnable example for you to look at:
class Outer {
function runner(){
$this->runCallback([new class {
function anonymousClassMethod(){
echo "hi from anonymous class method";
}
}, 'anonymousClassMethod']);
}
function runCallback(callable $f){
$f();
}
}
$o = new Outer();
$o->runner();
I see 2 issues with your code.
You are not using the right method on $util
Instead of
$util->setLogger()->log('Phil runs very fast');
your code should be $util->getLogger()->log('Phil runs very fast');.
You want to getLogger since it was already set before.
Your implementation of getLogger() might be flawed
In my opinion, this method should not have any parameter and it should return something, which is actually missing in your code.
So instead of
public function getLogger($logger) {
$this->logger = $logger;
}
you should have something like
public function getLogger() {
return $this->logger;
}
With those 2 points addressed, your code works as expected. See here for yourself https://ideone.com/V2slho.

Oddity of static:: calling a method that contains $this

In this example I get the fatal error "Fatal error: Using $this when not in object context" as expected
class ctis_parent{
public function objFunc(){
var_dump('Called succes');
}
public static function call(){
$this->objFunc();
}
public function __construct(){
self::call();
}
}
new ctis_parent();
But if remove static keyword from definition of call() method all work fine, why?
class ctis_parent{
public function objFunc(){
var_dump('Called succes');
}
public function call(){
$this->objFunc();
}
public function __construct(){
self::call();
}
}
new ctis_parent();
//string 'Called succes' (length=13)
A static function, by definition doesn't need the class being instantiated, so it doesn't have access to the $this-> reference, which points to the current instance. If an instance doesn't exist, it can't be pointed to. Makes sense.
Because you're using $this when you're not in an object. Well, you're not REALLY, but with the static declaration, people could do:
ctis_parent::call();
Where, $this would be illegal.
See the docs for static.

PHP static classes problem

<?php
class jokz {
static public $val='123';
static public function xxx() {
jokz2(self);
}
}
function jokz2($obj) {
echo $obj::$val;
}
jokz::xxx();
?>
it returns fatal error, cause the class "self" couldn't be found...
so.. how can i make that work?
passing a parameter by reference in function also don't work
function jokz2(&$obj) {
echo $obj::$val;
}
There is no object to pass (self refers to static class). You can pass the name of the class and call it that way (using call_user_func) or instantiate an object and pass $this
You would have to use $this to use the current object.

Categories