PHP get static methods - php

i want to call a class method by a var (like this):
$var = "read";
$params = array(...); //some parameter
if(/* MyClass has the static method $var */)
{
echo MyClass::$var($params);
}
elseif (/* MyClass hat a non-static method $var */)
{
$cl = new MyClass($params);
echo $cl->$var();
}
else throw new Exception();
i read in the php-manual how to get the function-members of a class (get_class_methods). but i get always every member without information if its static or not.
how can i determine a method´s context?
thank you for your help

Use the class ReflectionClass:
On Codepad.org: http://codepad.org/VEi5erFw
<?php
class MyClass
{
public function func1(){}
public static function func2(){}
}
$reflection = new ReflectionClass('MyClass');
var_dump( $reflection->getMethods(ReflectionMethod::IS_STATIC) );
This will output all static functions.
Or if you want to determine whether a given function is static you can use the ReflectionMethod class:
On Codepad.org: http://codepad.org/2YXE7NJb
<?php
class MyClass
{
public function func1(){}
public static function func2(){}
}
$reflection = new ReflectionClass('MyClass');
$func1 = $reflection->getMethod('func1');
$func2 = $reflection->getMethod('func2');
var_dump($func1->isStatic());
var_dump($func2->isStatic());

One way I know of is to use Reflection. In particular, one would use ReflectionClass::getMethods as such:
$class = new ReflectionClass("MyClass");
$staticmethods = $class->getMethods(ReflectionMethod::IS_STATIC);
print_r($staticmethods);
The difficulty of this is that you need to have Reflection enabled, which it is not by default.

Related

Is there a way to check if class member access on instantiation?

So in PHP 5.4 and up you can call a method on instantiation like so.
$class = new Foo()->methodName();
I would like to check when the class is instantiated if it was done so with a method at the same time.
Is it possible to check if the class was instantiated without a method at the same time and default to a method if not?
you can use instanceOf on the object for which you wanted to check the class.
Constructor of the class cannot return a value in php, so you can't use singleton incapsulated in constructor and have it looks nice. Of cource, you can make something like this
// NOT FOR USE
class Foo {
private static $instance;
public function __construct($skipIncapsulate = false) {
if (!$skipIncapsulation && !self::$instance)
{
self::instance = new self(true);
}
}
public function bar() {
// Do what you want with self::$instance
}
}
N.B. Do not use the example above, it is ugly solution, which also incapsulates unnecessary logic in controller, and while working with the class
Better use a usual singleton like this
class Foo {
private static $instance;
private function __construct()
{}
public static getInstance()
{
return self::$instance ?? self::$instance = new self();
}
}
Nevertheless you can create a new class FooManager, which will delegate the if the Foo class is defined
class FooManager {
private static $foo;
public function __construct()
{
self::$foo = self::$foo ?? self::$foo = new Foo();
}
public function getFoo()
{
return self::$foo;
}
}
// usage in your code
(new FooManager)->getFoo()->bar();
// You can add __call method to use (new FooManager)->foo->bar()
This will simplify working with your code. Incapsulating static self-instance in constructor is not the good practice

Reference static class method given class name as string in PHP5.5

I have a variable that holds a class name.
public $modelClass = 'common\models\Notecard';
That class has a static method.
public static function do_something() { ... }
Given this information, I would like to call the static function. For non-static functions, I can do the following:
$model_name = $this->modelClass;
$model = new $model_name();
$model->do_something_else();
Yes, that is pretty easy:
You can either just call the function from your instance e.g.
$model_name = $this->modelClass;
$model = new $model_name();
$model::do_something();
or using call_user_func()
call_user_func([$modelClass, 'do_something']);
You can use $model_name::do_something_else().
class foo {
public static function bar() {
echo "Called bar";
}
}
$fname = "foo";
$fname::bar();
Outputs Called bar
Works on php7.

calling method in another class in php

I am new to php and trying to call a function in another class.
How do I call function1 and function2 in class xyz???
class abc {
private $lmn = "lmn";
private $say1;
private static $static;
private function __construct(){
$say1 = print $this->lmn;
}
public static function1(){
$static = "YEAAHHHH";
}
public function function2(){
return $this->say1;
}
file 2:
require 'abc.php';
class xyz {
/**
* $e = new xyz();
*
*/
$e = xyz:: function1();// error
$d = xyz:: function 2(); //error
}
Also under what circumstance I should use
$obj = new class();
$obj->functionname();
and
$obj = class::functionname();
You have 2 different types of methods here, static and non-static.
To call the static (function1())
You don't need to instantiate the class, as it's static.
class zyx {
public function foo() {
return abc::function1();
}
}
To call the non-static (function2())
You need to instantiate the class, as it's not static.
class zyx {
public function foo() {
$abc = new abc();
return $abc->function2();
}
}
You would call function1 like:
abc::function1();
It is a method in abc not xyz.
function2() you would only call if you had an instance of abc because it is an instance method and not a static method. I.e.
$abc = new abc();
$abc->function2();
Static functions are intended to be called on classes, instance methods (i.e. function2() are intended to be called on instances of classes. I would recommend reading http://php.net/manual/en/oop5.intro.php.
Static functions can be called without instantiating your class...
$myClass::function1();
Non-static functions need to be instantiated first:
$myClass = new abc();
$myClass->function2();
So in your example:
require 'abc.php';
class xyz {
public function CallFunc1()
{
abc::function1();
}
public function CallFunc2()
{
$myClass = new abc();
$myClass->function2();
}
}
require 'abc.php';
class xyz {
public function static(){
return abc:: function1();// this is a static function
}
public function nonstatic(){
$e = new abc();
return $e->function2();
}
}
First of all, you can't have a space between function and 2():
$d = xyz::function2(); //correct
$d = xyz::function 2(); //very incorrect
I was going to have a second of all, but #hd beat me to it.
I think you have messed up with the code. I can share something with something that I found very helpful as an answer for your second question. Spend a bit time reading this. This is very basic, simple and well guided.
http://code.tutsplus.com/tutorials/object-oriented-php-for-beginners--net-12762

calling a class function from another class function

I'm new to programming. I have this going on:
I have Class A, which have many functions. One of those functions is functionX.
In functionX I need to make a call to functionY which belongs to another class: Class B.
So how do I acces to functionY from inside functionX?
I use Codeigniter.
Thanks in advance.
Try and experiment with this.
class ClassA {
public function functionX() {
$classB = new ClassB();
echo $classB->functionY();
}
}
class ClassB {
public function functionY() {
return "Stahp, no more OO, stahp!";
}
}
Class function? A static method?
If you have an instance (public) method, you just call $classB->functionY().
If you have a static method, you would call ClassB::functionY();
So:
class ClassA {
public function functionX(){
$classB = new ClassB();
// echo 'foo';
echo $classB->functionY();
// echo 'bar';
echo ClassB::functionYStatic();
}
}
class ClassB {
public $someVar;
public static $someVar2 = 'bar';
function __construct(){
$this->someVar = 'foo';
}
public function functionY(){
return $this->someVar;
}
public static function functionYStatic(){
return self::$someVar2;
}
}
Well that depends. If that function is a static function or not.
First off you must include the file with the class...
include_once('file_with_myclass.php');
If it is static you can call it like this:
ClassName::myFunction()
If it is not, then you create an instance of the class and then call the function on that instance.
$obj = new ClassName();
$obj->myFunction();
As you can guess the function being static means you can call it without the need of creating an instance. That is useful for example if you have a class Math and want to define a function that takes to arguments to calculate the sum of them. It wouldn't really be useful to create an instance of Math to do that, so you can declare as static and use it that way.
Here's a link to the docs with further info
http://www.php.net/manual/en/keyword.class.php
If functionY is static you can call ClassB::functionY(). Else you must create instance of Class B first. Like:
$instance = ClassB;
$instance->functionY();
But maybe you mean something else?
Looks like one of your class has a dependency to another one:
<?php
class A
{
public function x()
{
echo 'hello world';
}
}
class B
{
private $a;
public function __construct(A $a)
{
$this->a = $a;
}
public function y()
{
$this->a->x();
}
}
$a = new A();
$b = new B($a);
$b->y();
Depending how your code looks like, if it makes sense, you can inject class A into y()
public function y(A $a)
{
// your code with $a
}

typecasting in php

I have an interface in PHP
interface IDummy{
public function DoSomething();
}
I have another class that implements this interface.
class Dummy implements IDummy{
public function DoSomething(){
}
How can I type cast the Dummy Object to IDummy in PHP, so that I can call it as
$dum = new Dummy();
$instance = (IDummy)$dum;
$instance->DoSomething();
Can I do this in PHP?
Thanks and Regards
Abishek R Srikaanth
The cast is completely unnecessary. It will simply work.
And the Dummy objects will be considered an instance of IDummy if you ever check it with one of the various type hinting functions.
This works... no casting needed:
interface I {
public function foo();
};
class A implements I {
public function foo() { }
}
function test(I $obj) {
$obj->foo();
}
$a = new A();
test($a);
If class Dummy already implements interface IDummy, there's no need to cast $dum to IDummy - just call method DoSomething().
interface IDummy
{
public function doSomething();
}
class Dummy implements IDummy
{
public function doSomething()
{
echo 'exists!';
return;
}
}
$dummy = new Dummy();
$dummy->doSomething(); // exists!
The code should simply be:
$class = new ClassName;
$class->yourMethod();
As #konforce pointed out, not typecasting is required. You might want to check PHP method_exists() function http://php.net/manual/en/function.method-exists.php.
Well, it could be fun, see java functionality regarding this issue.
interface I {
public function foo();
};
class A implements I {
public function foo() { echo 'This should be accessible.'; }
public function baz() { echo 'This should not be available.'; }
}
$dum = new A();
$instance = (I) $dum;
$instance->foo(); // this should work
$instance->baz() // should not work
Note: This code throws error. It seems that you can not cast interface like that. In java is possible.
If you know the class name from the configuration or something else that you don't know, I think this should work:
$classname = 'Dummy';
$reflectionClass = new \ReflectionClass($classname);
$instance = $reflectionClass->newInstance();
// $dum = new $className; //you can do this as well I guess
if( $instance instanceof IDummy){
$instance->DoSomething();
}

Categories