I would like to know how I can dynamically execute a method in my class using the following string.
$model = "Shop\Cart\Models\Cart#getInfo";
my idea is to save this command in the database, and then dynamically call the command and get the data return..
My difficulty is how to execute this command, is it possible?
An alternative I did is to explode the # and then use the call_user_func method, but I would like to know if there is any way without using explodes and making the request directly.
Define classname first
$className = 'Shop\Cart\Models\Cart';
Then call the method
(new $className())->getInfo();
You can make a function which can extract class and method name and call afterwards.
<?php
$model = "Cart#getInfo";
function make($str) {
$a = explode("#", $str);
$c = new $a[0];
return $c->{$a[1]}();
}
class Cart {
public function getInfo() {
return "Hello World";
}
}
$res = make($model);
print_r($res);
output
// Hello World
Try to use eval()
<?php
require_once './Classes/MyClasses.php';
function e($string)
{
$string = str_replace('#', '::', $string);
return eval($string . '();');
}
$a = e('Classes\MyClasses\MyClass#test'); // test
?>
file ./Classes/MyClasses.php contains next:
<?php
namespace Classes\MyClasses;
class MyClass
{
public static function test()
{
echo 'test';
}
}
?>
Related
Is there a way I can include(?) one function into another? For example, the same way we can include files using include function.
Thank you.
<?php
class test{
public function message1(){
$message = 'i am in message1 function';
return $message;
}
public function message2(){
$message = $this->message1();
echo $message;
}
}
Functions can not be "included" like you mean but you can call them and use their returned values to other functions like below.
Now if you try to call the message2 function using something like:
$messageClass = new test();
echo $messageClass->message2();
you will see that the output is the $message from function message1
Do you mean callback function? If so, this is how to use it:
// This is callback function which will passed as argument to another function.
function callbackFunction1 ($str) {
return strtoupper($str);
}
function mainFunction ($offeredCallback, $str) {
echo( "(" . $offeredCallback($str) . ")<br>");
}
mainFunction("callbackFunction1", "foo");
// Output "(foo)".
// If you want to use Variable Function, define it like this:
$callbackFunction2 = function ($str) {
return strtoupper($str);
};
mainFunction($callbackFunction2, "bar");
// Output "(bar)".
About Variable Function, see Anonymous Function.
Is it possible to get the line and file where a object is created?
For example.
I know the print PHP error outputs where a error occurred and at which line. Is it possible to use that mechanism?
Sending the file to the object is easy. I can just use basename(__FILE__) as an argument. But I would prefer if the object arguments can remain empty. Like this:
Foo.php
<?php
class Foo {
public $line = null;
public function __construct(){
$this->line = where_object_is_assigned
}
}
?>
Index.php
<?php
$object = new Foo();
echo $object->line // Output Index.php line 3
?>
Is there a way for the object to access this data without sending it?
Thanks in advance
I solved it by using the function debug_backtrace();
<?php
class Foo {
public $line = null;
public function __construct(){
$bt = debug_backtrace();
$caller = array_shift($bt); // Get first array
$this->line = $caller["line"];
}
}
?>
Index.php
<?php
$object = new Foo();
echo $object->line // Output: 3
?>
The function must be used in __construct() else it won't work.
Read more here: http://php.net/manual/en/function.debug-backtrace.php
This will output on which line-number the object is created
Class
class Foo {
public $line = NULL;
public function __construct($line){
$this->line = $line;
}
}
Index.php
<?php
$object = new Foo(__LINE__); //Will output 1
echo $object->line;
PHP provides a large number of predefined constants to any script which it runs. Within this you can simply find the predefined constant named as LINE
__LINE__ The current line number of the file.
So you need to simply use the predefined constant within your code like as
<?php
class Foo {
public $line = __LINE__;
}
$object = new Foo();
echo $object->line;
?>
After 9 hours of struggling to get this right, I have turned to the internet for help. I can't seem to find any relevant answers doing a Google search.
I currently have a class called Test. Test accepts a single argument.
<?php
class test {
private $varpassed;
public function getVarpas() {
return $this->varpassed;
}
Public function setVarpas($value) {
$this->varpassed= $value;
}
public function stringGen(){
$testvar = $this->varpassed;
echo $testvar;
}
}
The stringGen function should return the $varpassed variable whenever its called. The value for $varpassed is set using the setVarpas function. However, when ever I call the stringGen() method I only seem to be getting the following error:
Fatal error: Using $this when not in object context in file.php line 14.
Pointing to this line:
$testvar = $this->varpassed;
Is there any other way to pass the variable to the stringGen method? I've tried using:
self::$this->varpassed;
Which also throws an error.
first create an instance of the object (so you can use $this in the context), for example:
$test = new test();
then you can call:
$test->setVarpas('Hello World!');
now you can call:
$test->stringGen();
you have to do something like this
$var = new test();
$var->setVarpas("Hello");
$var->stringGen(); // this will echo Hello
$this is used when you are withing class. outside class you have to use class object.
1) Change this: class test() to class test
2) Create and instance first something like $t1 = new test();
3) Call the function $t1->setVarpas(5);
4) Now you can call the function $t1->stringGen();
Fixed:
<?php
class test
{
private $varpassed;
public function getVarpas() {
return $this->varpassed;
}
Public function setVarpas($value) {
$this->varpassed= $value;
}
public function stringGen(){
$testvar = $this->varpassed;
echo $testvar;
}
}
$t1 = new test();
$t1->setVarpas(5);
$t1->stringGen();
OUTPUT:
5
You should not declare a class with parentheses.
Use
class test {
instead of
class test(){
I'm trying to do something like this:
function doSomething($param, Class) {
Class::someFunction();
}
$someVar = doSomething($param, Class);
Is it possible?
To explain better what I'm trying to do. I have a helper function in Laravel to generate unique slugs, so I have to query different tables depending on where the slug is going to be saved.
Actual code I'm trying to write:
$newcat->slug = $helper->uniqueSlug($appname, Apk);
public function uniqueSlug($str, Apk)
{
$slug = Str::slug($str);
$count = Apk::whereRaw("slug RLIKE '^{$slug}(-[0-9]+)?$'")->count();
return $count ? "{$slug}-{$count}" : $slug;
}
Thanks!
You can use the magic ::class constant:
public function uniqueSlug($str, $model)
{
$slug = Str::slug($str);
$count = $model::whereRaw("slug RLIKE '^{$slug}(-[0-9]+)?$'")->count();
return $count ? "{$slug}-{$count}" : $slug;
}
$newcat->slug = $helper->uniqueSlug($appname, Apk::class);
In PHP, classes (or class names) are handled as strings. Since PHP 5.5, you can use YourClass::class to get a fully qualified class name.
If you want to get it in an earlier version of php, you can (if you have already an object of the calss) either do the following:
<?php
$obj = new YourClass();
// some code
$clazz = get_class($obj);
?>
or, you can implement a static method in your class, like this:
<?php
class YourClass {
// some code
public static function getClassName() {
return get_called_class();
}
?>
If you want to pass a class to a function, you can do it like this:
<?php
function do_somthing($arg1, $clazz) {
$clazz::someStaticMethod($arg1);
}
?>
or
<?php
function do_somthing($arg1, $clazz) {
call_user_func(array($clazz, 'someStaticMethod')), $arg1);
}
?>
If you need to call a non-static method of that class, you need to instanciate it:
<?php
function do_somthing($arg1, $clazz) {
$obj = new $clazz();
$obj->someNonStaticMethod();
}
?>
Note: You can use PHP type hinting with passed class names:
<?php
function do_somthing($arg1, MyInterface $clazz) {
$obj = new $clazz();
$obj->someInterfaceMethod();
}
?>
I think you can.
Send the class name as string parameter then use it like below.
$classtr = "yourparam";// param comes from the function call.
$obj = new $classtr;
$obj->method();
Send the class name as string parameter you need use the namespace. For example:
function defineClass()
{
$class = "App\MyClass"; // mention the namespace too
}
function reciveClass($class)
{
$class:: // what do you need,
}
I have a class and I am including the players.php file inside it.
class My_Class {
private $player_types;
public function __construct() {
$this->player_types = 'classic';
require_once('players.php');
}
public function getPlayerTypes() {
return $this->player_types;
}
}
$mc = new My_Class();
How can I call getPlayerTypes function from players.php?
Also if its better to maybe use static method?
Just write :
$result = $this->getPlayerTypes();
echo $result;
inside the players.php. Definitely this will work.
Since the getPlayerTypes() is a method defined in the class My_Class, if you want to call that method from players.php you should instantiate a new My_Class object in that file and call the getPlayerTypes() there.
//player.php
$mc = new My_Class();
$playerTypes = $mc->getPlayerTypes();
echo $playerTypes
and remove that
require_once('players.php');
from your class :)
Since you are instantiating the class with the variable $mc, you'd call the function using
$mc->getPlayerTypes();
Or you can assign a variable to the result,
$result = $mc->getPlayerTypes();
echo $result;