PHP: Dynamically call default method - php

There's the following (example) class:
class klasse
{
private $var = 'doit';
function doit($param)
{
return md5($param);
}
function bla($param)
{
// HERES THE PROBLEM
return $this->{$this->var}($param);
}
}
// Create new instance
$klasse = new klasse;
// Start the "dynamical output"
echo $klasse->bla('test');
This works fine! But the problem is that I'd like to call the md5() function "directly dynamically". So I don't want to go the detour with "doit()".
If I try
private $var = 'md5';
at the beginning of the class I get the following (absolutely senseful) error message:
Fatal error: Call to undefined method klasse::md5() in - on line 13
So I know that this error is senseful but I have no clue how to avoid it?
How can I handle this (to directly call md5())?
Thank you!

This should work:
class klasse
{
public function __construct() {
$this->var = 'md5';
}
}
$klasse = new klasse;
echo call_user_func($klasse->var, 'argument');
More info at: http://php.net/manual/en/function.call-user-func.php

Related

how to use function from another class in flight php

I am new in flight php.
I need some help, I create two classes client.class.php and deliveryServiceConnector.class.php and i have index.php. I want to use function from deliveryServiceConnector.class.php in client.class.php so I write this code:
public function __construct() {
$this->connector = new deliveryServiceConnector(DOLIBARR_API_KEY,DOLIBARR_ROOT_URL,NuLL, $this->nodeName);
$connector->testDisplayDev();
}
I got this error:
Undefined variable: connector (8)
Any idea how can i fix my error, Thanks
You're not using the same thing for the deliveryServiceConnector. In the first line, inside the function, you use $this->connector, but in the second line you use $connector. Therefore it is undefined. Try to use the same thing twice. Either:
public function __construct() {
$this->connector = new deliveryServiceConnector(DOLIBARR_API_KEY,DOLIBARR_ROOT_URL,NuLL, $this->nodeName);
$this->connector->testDisplayDev();
}
or
public function __construct() {
$connector = new deliveryServiceConnector(DOLIBARR_API_KEY,DOLIBARR_ROOT_URL,NuLL, $this->nodeName);
$connector->testDisplayDev();
}

php object instantiation with variable after it, such as the type seen in Laravel?

I see and use this syntax alot in Laravel, I wonder how it works, cause I try to integrate it in my own project but I get errors like this
FATAL ERROR Uncaught TypeError: Argument 1 passed to getVal() must be an instance of Man, none given, called in'
now here is Laravel type code as you all know
public function join(Request $request){
echo $request['name'];
//for instance
}
and it works fine, now here is my code:
class Man {
public $child,
$wife;
public function _construct(){
$this->child = 1;
$this->wife = 2;
}
}
function getVal(Man $man){
echo $man->wife;
}
getVal();
Please help me understand this better.
As the error says, the value passed to getVal() must be an instance of Man, so your last line of getVal() needs to have an instance of Man passed to it.
It can be any instance of man, or itself:
$man = new Man();
getVal($man)
would also work
as would:
$man = new Man();
$man2 = new Man();
getVal($man2)
This is a normal way of writing PHP code.
However, there may be something else going on in Laravel, if you could link the location in the source code, that'd be great.
Possibly wrong, but its piece of code, that could help you to find direction. Its not working, dunno how to return back to normal code.
<?php
set_exception_handler('myExcHandler');
function myExcHandler(Throwable $exception) {
$fr = new ReflectionFunction($exception->getTrace()[0]['function']);
$parameters = [];
$st = new MyStaticClasses();
foreach ($fr->getParameters() as $parameter) {
$parameters[] = $st->getClass($parameter->name);
}
return call_user_func_array($exception->getTrace()[0]['function'], $parameters);
}
class Man {
public $wife = 1;
}
class MyStaticClasses {
public $storage;
public function __construct() {
$this->storage['man'] = new Man();
}
public function getClass($name) {
return $this->storage[$name];
}
}
function getVal(Man $man) {
return $man->wife;
}
echo getVal();

Attempt to assign property of non-object error

I am getting this error and i can't see what i am doing wrong. I have done the same thing with other objects from other classes which are built in the exact same way and i can't see why i am getting this error now.
The code in which i create the object is this one:
$consulta2 = "SELECT * FROM TiposDireccion WHERE Cliente_CIF='$cif' and Direccion_Direccion='$direccion' and Direccion_CP=$cp ";
echo($consulta2."</br>");
if ($resultado2 = $conexion->query($consulta2)){
while($fila2 = $resultado2->fetch_object()){
$tipodireccion78=$fila2->TipoDireccion_Tipo;
//we see here that the select is returning a correct string with a correct value
echo($tipodireccion78);
//we try to instantiate and it fails =(
$unTipoDireccion=TipoDireccion::constructor1($tipodireccion78);
This is the class TipoDireccion:
<?php
class TipoDireccion{
private $tipo;
private $descripcion;
//Construct auxiliar
function __construct() {
}
//Constructor 1 : completo
function constructor1($tipo) {
$tipoDireccion = new TipoDireccion();
$tipoDireccion->tipo = $tipo;
return $tipoDireccion;
}
function ponTipo($tipo) {
$this->tipo = $tipo;
}
function devuelveTipo() {
return $this->tipo;
}
function ponDescripcion($descripcion) {
$this->descripcion = $descripcion;
}
function devuelveDescripcion() {
return $this->descripcion;
}
}
?>
Thank you a lot in advance!
Don't know if this is still relevant to you, but in case anyone else comes on here for an answer. The problem is in this function:
function constructor1($tipo) {
$tipoDireccion = new TipoDireccion();
$tipoDireccion->tipo = $tipo;
return $tipoDireccion;
}
Because in the class definition, you define private $tipo; and then you try and assign $tipoDireccion->tipo to what was passed through the function. However, you aren't trying to access that variable through the scope of the class, you are trying to assign it from the 'public' scope as far as the class is concerned.
The fix for this has two options, the first one would be to change private $tipo; to public $tipo;. But that isn't a good solution as you have an assignment function for it.
Instead, use your functions that you made, which would make the function look like:
function constructor1($tipo) {
$tipoDireccion = new TipoDireccion();
$tipoDireccion->ponTipo($tipo);
return $tipoDireccion;
}
That's how you need to access it from the public scope, which you are doing after you initiate a new one.
function constructor1($tipo) {}
should be
static function constructor1($tipo) {}

Pass the current class as parameter

I have a class like this:
// file /models/person.php
class Person
{
public function create_path()
{
self::log();
path_helper($this); //a global function in other php file
}
public function log()
{
echo "trying to create a path";
}
}
This is the way how Person is instanciated:
//file /tools/Builder.php
include('/models/Person.php');
class Builder
{
public function build()
{
$type = 'Person';
$temp = new $type();
$temp->create_path();
}
}
As you note in Person class, I am calling the object in question with $this reference. But this is not correct because an error is showed:
Message: Undefined variable: this
I suppose that $this reference point to other object or it is unable to work because the object is created from another script. Also, I tried to use self because there was not problem calling methods with that, but as parameter I get:
Message: Use of undefined constant self - assumed 'self'
So, can you guide me to the right direction?
I tested your code out for myself, with a few minor changes. It appears to work properly.
Changed self::log() to $this->log()
Added global function path_helper (I have no idea what this does)
PHP
function path_helper(Person $object)
{
var_dump($object);
}
class Person
{
public function create_path()
{
$this->log();
path_helper($this); //a global function in other php file
}
public function log()
{
echo "trying to create a path";
}
}
class Builder
{
public function build()
{
$type = 'Person';
$temp = new $type();
$temp->create_path();
}
}
$Build = new Builder();
$Build->build();
Result
trying to create a path
object(Person)[2]
Your code is correct and your going in the right direction.
You should call the log method like this:
$this->log();
because using self:: is reserved for static methods.
Also, try calling the path_helper function like this:
path_helper(self);
Hope I could help you. Couldn't test it, but it should work.

PHP - runkit redefine method

all my websites share a common starter, that deals with urls, file locations, etc.. There are 3 cases that need to be handled - is directory, file exists and file does not exist. Each application has unique code for each case. I decided to tinker with runkit a bit and I am trying to unify the code. Each case will be handled by a function, that could be redefined via runkit.
Consider this code:
class start {
function __construct() {
$this->options = array();
}
public function process() {
// some code here
$this->file_not_exists();
}
public function file_not_exists() {
$this->options['page'] = 222;
}
public function redefine($what, $code) {
runkit_method_redefine(get_class($this), $what, '', $code, RUNKIT_ACC_PUBLIC);
}
}
$start = new start();
$start->redefine('file_not_exists', '$this->options["page"] = 333;')
// page is now 333
This part works as intended. But when I try to change the code so the redefined method calls user function it works. But, for the love of god, I cant figure out how to pass the $this to the function.
Redefine method looks like this:
public function redefine($what, $code) {
runkit_method_redefine(get_class($this), $what, '', 'call_user_func('.$code.'(), '.$this.');', RUNKIT_ACC_PUBLIC)
}
This doesn't work, no matter what I try (call_user_func_array as well). I just cant figure it out. For the record:
public function redefine($what, $code) {
my_user_function($this);
}
Does work.
Any help is appreciated.
Note that this is just an experiment and I would like to know how to do this :)
Edit:
I get:
Catchable fatal error: Object of class starter could not be converted to string in blablallala\rewrite_starter2.php on line 153
{... removed as not necessary ...}
==== EDIT =====
[For the new problem, what you need is this]
<?
class start {
function __construct() {
$this->options = array();
}
public function process() {
// some code here
$this->file_not_exists();
}
public function file_not_exists() {
$this->options['page'] = 222;
}
public function redefine($what, $code) {
runkit_method_redefine(get_class($this),
$what,
'',
'call_user_func(array($this,' .$code. '),$this);',
RUNKIT_ACC_PUBLIC);
}
public function my_func($someobj)
{
print_r($someobj);
}
}
$start = new start();
$start->redefine('file_not_exists', 'my_func');
$start->process();
?>
The documentation on the call_user_func function says that the first argument is 'callable'. So to call the class method dynamically, you should pass the array($obj, 'func_name').

Categories