I have a PHP class that looks like this:
class userAuthentication
{
public static function Authenticate()
{
if (isset($_COOKIE['email']))
{
verify($someVar, getPass($_COOKIE['email']);
}
}
public static function getPass($email)
{
}
public static function verify()
{
}
}
At times (I can't pin-point exactly when), I get a fatal error :
Call to undefined function getPass()
The error is thrown at the line where I call the function in the above code sample. Why is this happening when the function clearly exists.
It's a static function in a class. Use self::getPass() or static::getPass() if you want to take advantage of Late Static Binding. Same goes for verify().
verify is not a global function, but only valid in the scope of your class. You want
self::verify($someVar, getPass($_COOKIE['email']);
I would assume the error occurs when you try to run getPass($_COOKIE... since you're calling it wrong. Since the function is a class method, you have to run it like this:
$this->getPass(...);
or if you're calling it statically:
self::getPass(...);
Making your code:
class userAuthentication
{
public static function Authenticate()
{
if (isset($_COOKIE['email']))
{
self::verify($someVar, self::getPass($_COOKIE['email']);
// Or...
$this->verify($someVar, $this->getPass($_COOKIE['email']);
}
}
public static function getPass($email)
{
}
public static function verify()
{
}
}
You're not calling it as a static function.
From within the class use either:
self::getPass($email);
or (for late static binding):
static::getPass($email);
and from outside the class:
userAuthentication::getPass($email);
The line should probably be:
self::verify($someVar, self::getPass($_COOKIE['email']);
Related
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.
I'am trying to make a reference to a static function inside a class:
class Test {
function __construct() {
$this->fn1 = self::fn2;
}
public static function fn2() {
}
}
then i get this error:
Undefined class constant 'fn2'
why?
Not sure if this is what you want, but at least this might give you a hint:
<?php
class Test {
function __construct() {
$this->fn = function(){
return self::realFn();
};
}
public function callFn (){
$fn = $this->fn ;//yes, assigning to a var first is needed. You could also use call_user_func
$fn();
}
public static function realFn() {
echo 'blah';
}
}
$x = new Test();
$x->callFn();
You can test it here: https://3v4l.org/KVohi
You have defined a static function:
Test {
function__construct()
{
$this->fn1 = self::fn2();
}
public static function fn2()
{
}
}
Updated
If you want to assign a function to a variable, it is best to do this
with annonymous aka lambda functions since they are first class citizens and may be freely passed, returned and assigned. PHP is not unique in dealing with static method references in this fashion as JAVA implements them similarly:
Method references ... are compact, easy-to-read lambda expressions for
methods that already have a name.
You may create an anonymous function based on a callable in PHP, and so the OP may wish to do as follows, which PHP 7.1.10 or higher supports:
<?php
class Test {
public static function fn2() {
return __METHOD__;
}
public static function getClosure (){
return Closure::fromCallable(["Test","fn2"]);
}
}
echo Test::getClosure()(),"\n";
See live code here
In this example an anonymous function is created and returned by the static getClosure method. When one invokes this method, then it returns the closure whose content is the same as static method fn2. Next, the returned closure gets invoked which causes the name of static method fn2 to display.
For more info re closures from callables, see the Manual and the RFC.
With PHP 7 on up, you may create a complex callable. In the code below the complex callable is an invocable array:
<?php
class foo
{
public static function test()
{
return [__CLASS__, 'fn2'];
}
public static function fn2()
{
echo __METHOD__;
}
}
echo foo::test()();
See live code.
Note: Starting with PHP 7.0.23 you could create a complex callable using a string containing the class and method names separated by the double colon aka paaamayim nekudotayim; see here.
A solution that has broader PHP support is as follows:
<?php
class Test {
public static function fn2() {
return __METHOD__;
}
public static function tryme(){
return call_user_func(["Test","fn2"]);
}
}
// return closure and execute it
echo Test::tryme();
See live code
I have 2 file
file1.php
<?php
Class A
{
public static function _test
{
}
}
function get_sql($id)
{
}
function get_data($ids)
{
}
?>
In file2.php I've written
require_once('file1.php');
$a = get_sql($id);
Why I cannot call the function and get my result??
try this in file1.php
<?php
Class A {
public static function _test {
}
function get_sql($id) {
echo $id;
}
function get_data($ids) {
}
}
?>
In file2.php first require the file and then code this
require_once('file1.php');
$a = new A();
$a->get_sql($id);
OR send static value in function
$a->get_sql(5);
This is your first mistake in your code
public static function _test{
}
} //this bracket is related to the class
Well for one thing you are not returning anything from the get_sql($id) function.
Assuming you are returning something in your original code; I hope you are aware that the function is not part of the class (its defined outside the scope of the class). But for educational purposes you would call a static method within a class by doing:
$a = A::get_sql($id);
This would also mean the defining the function in the following manner:
Class A{
public static function get_sql($id){
echo $id;
}
}
it is the question if you want to have functions get_sql() and get_data() as a methods inside the A class:
If yes the code from user2727841 will work after you add the round brackets to the function public static function _test:
public static function _test()
{
}
Your code will work too after you add the same brackets to the same function but your function get_sql() and get_data() are outside the class A.
EDIT
I thought that these function are outside the class A.
Please, add the round brackets to the public static function _test in the class A - it is syntax error - than I hope it will work.
I have a problem which is probably not for most of you.
Sorry if it is obvious for you...
This is my code :
class Bat
{
public function test()
{
echo"ici";
exit();
}
public function test2()
{
$this->test();
}
}
In my controller:
bat::test2();
i have an error:
Exception information: Message: Method "test" does not exist and was
not trapped in __call()
Bat::test2 refers to a static function. So you have to declare it static.
class Bat
{
public static function test()
{
echo"ici";
exit();
}
// You can call me from outside using 'Bar::test2()'
public static function test2()
{
// Call the static function 'test' in our own class
// $this is not defined as we are not in an instance context, but in a class context
self::test();
}
}
Bat::test2();
Else, you need an instance of Bat and call the function on that instance:
$myBat = new Bat();
$myBat->test2();
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();