How can I call a method into a function of another method? - php

Here is my code:
class myclass{
public function one(){
return 'sth';
}
public function two(){
function myfunc($arg){
if ($arg){
return $this->one();
} else {
return 'nothing';
}
myfunc(true);
}
}
}
$obj = new myclass;
echo $obj->$this->two();
As you see in the fiddle it throws this error:
Fatal error: Uncaught Error: Using $this when not in object context in /in/E1U9n:25
How can I fix the problem? The expected result is sth.

First you're calling myfunc(true); in it's own scope.So it is not
possible to call a function in it's scope as far as i know
Secondly You're calling $this in a scope of function which doesn't know which class does it belong.
Thirdly you're not returning anything from your function two() so as it suppose. It will not echo anything.
See the fiddle https://3v4l.org/sl4eq
class myclass{
public function one(){
return 'sth';
}
public function two(){
function myfunc($arg){
if ($arg){
$newobj = new myclass();
return $newobj->one();
} else {
return 'nothing';
}
}
return myfunc(TRUE);
}
}
$obj = new myclass;
echo $obj->two();

Your code is really messy, because you lack of basic knowledge and experience. I strictly recommending for you to read the basics about OOP in PHP.
http://php.net/manual/en/language.oop5.php
<?php
class myclass {
public function one()
{
return 'sth';
}
public function two()
{
return $this->myfunc(true);
}
protected function myfunc($arg)
{
if ($arg)
return $this->one();
else
return 'nothing';
}
}
$obj = new myclass;
echo $obj->two();

Related

PHP - ReflectionFunction - Function Test::test_function() does not exist

I could use RefexionFunction outside of a class, but inside a class I get an exception.
Fatal error: Uncaught ReflectionException: Function Test::test_function() does not exist in test.php.
<?php
function parameters($functionName,$args){
$f = new ReflectionFunction($functionName);
....
}
class Test{
public function test_functionA($abc,$d,$e,$f) {
parameters(__METHOD__,func_get_args());
}
protected function test_functionB($abc,$d,$e,$f) {
parameters(__METHOD__,func_get_args());
}
private function test_functionC($abc,$d,$e,$f) {
parameters(__METHOD__,func_get_args());
}
}
$test = new Test();
$test->test_function('something',1,2,array(123,456));
?>
Appreciate your help.
Your error:
Fatal error: Uncaught ReflectionException: Function Test::test_function() does not exist in test.php.
Doesn't refer to the function name quite as you expect it to.
ReflectionClass docs says this:
The ReflectionClass class reports information about a class.
ref: https://secure.php.net/manual/en/class.reflectionclass.php
You want to use a combination of methods available in that class to get information about the passed method like this:
public function parameters($class, $fnc)
{
$f = new ReflectionClass($class);
if ($f->hasMethod($fnc)) {
return 'howdy folks';
} else {
return 'not so howdy folks';
}
}
You first pass the class before checking if the function exists. You can then use the built-in function hasMethod to check if the function exists. You then use the parameters function like this:
public function testFunction()
{
return $this->helper->parameters(__CLASS__, __FUNCTION__);
}
All together the code looks like this:
<?php
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
class paramsHelper
{
public function parameters($class, $fnc)
{
$f = new ReflectionClass($class);
$f->getMethod($fnc);
if ($f->hasMethod($fnc)) {
return 'howdy folks';
} else {
return 'not so howdy folks';
}
return $f;
}
}
class Test
{
protected $helper;
public function __construct($helper)
{
$this->helper = $helper;
}
public function testFunction()
{
return $this->helper->parameters(__CLASS__, __FUNCTION__);
}
}
$test = new Test(new paramsHelper());
echo '<pre>';
print_r($test->testFunction());
echo '</pre>';
One of your other problems is that __METHOD__ actually returns a string like this: Test::testFunction not testFunction - hence my use of __FUNCTION__ instead.
Edit:
To get the parameters of the passed method, change your parameters method to this:
class paramsHelper
{
public function getMethodParameters($class, $fnc)
{
$f = new ReflectionMethod($class, $fnc);
echo '<pre>';
print_r($f->getParameters());
echo '</pre>';
}
}
This uses ReflectionMethod in place of ReflectionClass - this is more inline with your intended use.
ref: https://secure.php.net/manual/en/class.reflectionmethod.php
use:
class paramsHelper
{
public function getMethodParameters($class, $fnc)
{
$f = new ReflectionMethod($class, $fnc);
echo '<pre>';
print_r($f->getParameters());
echo '</pre>';
}
}
class Test
{
protected $helper;
public function __construct($helper)
{
$this->helper = $helper;
}
public function testFunction($a = '', $b = 1, $c = 3)
{
return $this->helper->parameters(__CLASS__, __FUNCTION__);
}
}
$test = new Test(new paramsHelper());
echo '<pre>';
print_r($test->testFunction());
echo '</pre>';

PHP how can make an function like this? first()->callSecond();?

I try to make an function like this below how can do that, any example?
$myClass->first()->callSecond();
You just need to return object all the time. It's called fluent interface. It can be self or other object.
<php
class A
{
public function first()
{
// Do something
return $this;
}
public function callSecond()
{
// Do somewthing else
return $this;
}
}
$a = (new A())->first()->callSecond();
<?php
class OtherClass{
public function callSecond(){
echo 'Second Called';
}
}
class MyClass{
public function first(){
return new OtherClass();
}
}
$myClass = new MyClass();
$myClass->first()->callSecond();
?>

How to display a class from another class in PHP

How to display a class from another class in PHP ?
class Layout {
public $var;
public function __construct() {
$this->var = 'test';
}
public function __toString() {
return $this->var;
}
}
class Template {
private $var_layout;
public function __construct() {
$obj = new Layout;
$this->var_layout = $obj;
}
public function __toString() {
return $this->var_layout;
}
}
$template = new Template();
echo($template);
Error message: Method Template::__toString() must return a string value
Please help, thank you very much..
return $this->var_layout; in the Template class does not return a string, it returns an object. Make it return a string by calling the __toString() method of that object explicitly.

Find the class name of the calling function in php

Lets say I have:
class Zebra{
public static function action(){
print 'I was called from the '.get_class().' class'; // How do I get water here?
}
}
class Water{
public static function drink(){
Zebra::action();
}
}
Water::drink();
How do I get "water" from the zebra class?
(This is for php 5.3)
You can get the caller's info from debug_backtrace http://php.net/manual/en/function.debug-backtrace.php
One not so good solution is :
use __METHOD__ or __FUNCTION__ or __CLASS__ .
and pass it as parameter to function being called.
http://codepad.org/AVG0Taq7
<?php
class Zebra{
public static function action($source){
print 'I was called from the '.$source.' class'; // How do I get water here?
}
}
class Water{
public static function drink(){
Zebra::action(__CLASS__);
}
}
Water::drink();
?>
Full usable solution using exception, but not debug_backtrace, no need to modify any prototype :
function getRealCallClass($functionName)
{
try
{
throw new exception();
}
catch(exception $e)
{
$trace = $e->getTrace();
$bInfunction = false;
foreach($trace as $trace_piece)
{
if ($trace_piece['function'] == $functionName)
{
if (!$bInfunction)
$bInfunction = true;
}
elseif($bInfunction) //found !!!
{
return $trace_piece['class'];
}
}
}
}
class Zebra{
public static function action(){
print 'I was called from the '.getRealCallClass(__FUNCTION__).' class';
}
}
class Water{
public static function drink(){
Zebra::action();
}
}
Water::drink();

PHP Call a instance method with call_user_func within the same class

I'm trying to use call_user_func to call a method from another method of the same object, e.g.
class MyClass
{
public function __construct()
{
$this->foo('bar');
}
public function foo($method)
{
return call_user_func(array($this, $method), 'Hello World');
}
public function bar($message)
{
echo $message;
}
}
new MyClass; Should return 'Hello World'...
Does anyone know the correct way to achieve this?
Many thanks!
The code you posted should work just fine. An alternative would be to use "variable functions" like this:
public function foo($method)
{
//safety first - you might not need this if the $method
//parameter is tightly controlled....
if (method_exists($this, $method))
{
return $this->$method('Hello World');
}
else
{
//oh dear - handle this situation in whatever way
//is appropriate
return null;
}
}
This works for me:
<?php
class MyClass
{
public function __construct()
{
$this->foo('bar');
}
public function foo($method)
{
return call_user_func(array($this, $method), 'Hello World');
}
public function bar($message)
{
echo $message;
}
}
$mc = new MyClass();
?>
This gets printed out:
wraith:Downloads mwilliamson$ php userfunc_test.php
Hello World
new MyClass; Should return 'Hello World'...
A constructor does not return anything.

Categories