I'm looking for something like break for loops.
Here's some example code (using Symfony's lime) where stop() would not let the class continue and I_DONT_WANT_THIS_TO_RUN() would not be executed.
$browser->isStatusCode(200)
->isRequestParameter('module', 'home')
->isRequestParameter('action', 'index')
->click('Register')
->stop()
->I_DONT_WANT_THIS_TO_RUN();
$browser->thenThisRunsOkay();
Calling $this->__deconstruct(); from within stop() doesn't seem to do the trick. Is there a function I can call within stop() that would make that happen?
You could use PHP exceptions:
// This function would of course be declared in the class
function stop() {
throw new Exception('Stopped.');
}
try {
$browser->isStatusCode(200)
->isRequestParameter('module', 'home')
->isRequestParameter('action', 'index')
->click('Register')
->stop()
->I_DONT_WANT_THIS_TO_RUN();
} catch (Exception $e) {
// when stop() throws the exception, control will go on from here.
}
$browser->thenThisRunsOkay();
Just return another class which will return $this for every method called.
Example:
class NoMethods {
public function __call($name, $args)
{
echo __METHOD__ . " called $name with " . count($args) . " arguments.\n";
return $this;
}
}
class Browser {
public function runThis()
{
echo __METHOD__ . "\n";
return $this;
}
public function stop()
{
echo __METHOD__ . "\n";
return new NoMethods();
}
public function dontRunThis()
{
echo __METHOD__ . "\n";
return $this;
}
}
$browser = new Browser();
echo "with stop\n";
$browser->runThis()->stop()->dontRunThis()->dunno('hey');
echo "without stop\n";
$browser->runThis()->dontRunThis();
echo "the end\n";
Will result in:
with stop
Browser::runThis
Browser::stop
NoMethods::__call called dontRunThis with 0 arguments.
NoMethods::__call called dunno with 1 arguments.
without stop
Browser::runThis
Browser::dontRunThis
the end
OIS's answer is really good, though I could see that it might get confusing if the object suddenly changes to something else. That is, you'd expect that at the end of your chain, you'll end up with the same object. To avoid that problem, I'd add a private variable to tell the class whether or not to actually do anything. If the class has been stopped, then every class just returns $this straight away. This gives you the added benefit of being able to restart the execution.
class MyClass {
private $halt;
function __call($func, $args) {
if ($this->halt) {
return $this;
} else {
return $this->$func($args);
}
}
private function isRequestParameter() {
// ...
}
public function stop() {
$this->halt = true;
}
public function start() {
$this->halt = false;
}
}
This could be put into a parent class so you don't have to duplicate this code.
Related
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();
I'm trying to add methods dynamically from external files.
Right now I have __call method in my class so when i call the method I want, __call includes it for me; the problem is I want to call loaded function by using my class, and I don't want loaded function outside of the class;
Class myClass
{
function__call($name, $args)
{
require_once($name.".php");
}
}
echoA.php:
function echoA()
{
echo("A");
}
then i want to use it like:
$myClass = new myClass();
$myClass->echoA();
Any advice will be appreciated.
Is this what you need?
$methodOne = function ()
{
echo "I am doing one.".PHP_EOL;
};
$methodTwo = function ()
{
echo "I am doing two.".PHP_EOL;
};
class Composite
{
function addMethod($name, $method)
{
$this->{$name} = $method;
}
public function __call($name, $arguments)
{
return call_user_func($this->{$name}, $arguments);
}
}
$one = new Composite();
$one -> addMethod("method1", $methodOne);
$one -> method1();
$one -> addMethod("method2", $methodTwo);
$one -> method2();
You cannot dynamically add methods to a class at runtime, period.*
PHP simply isn't a very duck-punchable language.
* Without ugly hacks.
You can dynamically add attributes and methods providing it is done through the constructor in the same way you can pass a function as argument of another function.
class Example {
function __construct($f)
{
$this->action=$f;
}
}
function fun() {
echo "hello\n";
}
$ex1 = new class('fun');
You can not call directlry $ex1->action(), it must be assigned to a variable and then you can call this variable like a function.
if i read the manual right,
the __call get called insted of the function, if the function dosn't exist
so you probely need to call it after you created it
Class myClass
{
function __call($name, $args)
{
require_once($name.".php");
$this->$name($args);
}
}
You can create an attribute in your class : methods=[]
and use create_function for create lambda function.
Stock it in the methods attribute, at index of the name of method you want.
use :
function __call($method, $arguments)
{
if(method_exists($this, $method))
$this->$method($arguments);
else
$this->methods[$method]($arguments);
}
to find and call good method.
What you are referring to is called Overloading. Read all about it in the PHP Manual
/**
* #method Talk hello(string $name)
* #method Talk goodbye(string $name)
*/
class Talk {
private $methods = [];
public function __construct(array $methods) {
$this->methods = $methods;
}
public function __call(string $method, array $arguments): Talk {
if ($func = $this->methods[$method] ?? false) {
$func(...$arguments);
return $this;
}
throw new \RuntimeException(sprintf('Missing %s method.'));
}
}
$howdy = new Talk([
'hello' => function(string $name) {
echo sprintf('Hello %s!%s', $name, PHP_EOL);
},
'goodbye' => function(string $name) {
echo sprintf('Goodbye %s!%s', $name, PHP_EOL);
},
]);
$howdy
->hello('Jim')
->goodbye('Joe');
https://3v4l.org/iIhph
You can do both adding methods and properties dynamically.
Properties:
class XXX
{
public function __construct($array1)
{
foreach ($array1 as $item) {
$this->$item = "PropValue for property : " . $item;
}
}
}
$a1 = array("prop1", "prop2", "prop3", "prop4");
$class1 = new XXX($a1);
echo $class1->prop1 . PHP_EOL;
echo $class1->prop2 . PHP_EOL;
echo $class1->prop3 . PHP_EOL;
echo $class1->prop4 . PHP_EOL;
Methods:
//using anounymous function
$method1 = function () {
echo "this can be in an include file and read inline." . PHP_EOL;
};
class class1
{
//build the new method from the constructor, not required to do it here by it is simpler.
public function __construct($functionName, $body)
{
$this->{$functionName} = $body;
}
public function __call($functionName, $arguments)
{
return call_user_func($this->{$functionName}, $arguments);
}
}
//pass the new method name and the refernce to the anounymous function
$myObjectWithNewMethod = new class1("method1", $method1);
$myObjectWithNewMethod->method1();
I've worked up the following code example and a helper method which works with __call which may prove useful. https://github.com/permanenttourist/helpers/tree/master/PHP/php_append_methods
How would I go about ensuring that the overridden parent method exists before I call it?
I've tried this:
public function func() {
if (function_exists('parent::func')) {
return parent::func();
}
}
However the function_exists never evaluates to true.
public function func()
{
if (is_callable('parent::func')) {
parent::func();
}
}
I use this for calling parent constructor if exists, works fine.
I also use the following as a generic version:
public static function callParentMethod(
$object,
$class,
$methodName,
array $args = []
) {
$parentClass = get_parent_class($class);
while ($parentClass) {
if (method_exists($parentClass, $methodName)) {
$parentMethod = new \ReflectionMethod($parentClass, $methodName);
return $parentMethod->invokeArgs($object, $args);
}
$parentClass = get_parent_class($parentClass);
}
}
use it like this:
callParentMethod($this, __CLASS__, __FUNCTION__, func_get_args());
The way to do that, is:
if (method_exists(get_parent_class($this), 'func')) {
// method exist
} else {
// doesn't
}
http://php.net/manual/en/function.method-exists.php
http://php.net/manual/en/function.get-parent-class.php
<?php
class super {
public function m() {}
}
class sub extends super {
public function m() {
$rc = new ReflectionClass(__CLASS__);
$namepc = $rc->getParentClass()->name;
return method_exists($namepc, __FUNCTION__);
}
}
$s = new sub;
var_dump($s->m());
gives bool(true). Not sure if this would work if the method was defined in a superclass of super, but it would be a matter of introducing a simple loop.
How can i perform a function once a variable's value has been set?
say like
$obj = new object(); // dont perform $obj->my_function() just yet
$obj->my_var = 67 // $obj->my_function() now gets run
I want the object to do this function and now having to be called by the script.
Thanks
EDIT
my_var is predefined in the class, __set is not working for me.
Use a private property so __set() is invoked:
class Myclass {
private $my_var;
private $my_var_set = false;
public function __set($var, $value) {
if ($var == 'my_var' && !$this->my_var_set) {
// call some function
$this->my_var_set = true;
}
$this->$var = $value;
}
public function __get($var, $value) {
return $this->$name;
}
}
See Overloading. __set() is called because $my_var is inaccessible and there is your hook.
I'd recommend to create a setter function for $obj and include the relevant function call there. So basically your code would look somehow like this:
$obj = new ClassOfYours();
$obj->setThatValue("apple");
Of course you would have to take care that all assignments to ThatValue need to be
done through that setter in order make it work properly. Assuming that you're on php5 I'd set that property to private, so all direct assignments will cause an runtime error.
A good overview about OOP in php can be found in this article on devarticles.com.
HTH
To acheive exactly what you describe, you'd have to use a magic setter.
class ObjectWithSetter {
var $data = array();
public function my_function() {
echo "FOO";
}
public function __set($name, $value) {
$this->data[$name] = $value;
if($name == 'my_var') {
$this->my_function();
}
}
public function __get($name) {
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
$trace = debug_backtrace();
trigger_error(
'Undefined property via __get(): ' . $name .
' in ' . $trace[0]['file'] .
' on line ' . $trace[0]['line'],
E_USER_NOTICE);
return null;
}
/** As of PHP 5.1.0 */
public function __isset($name) {
return isset($this->data[$name]);
}
public function __unset($name) {
unset($this->data[$name]);
}
}
Assuming you want to call my_function() once you set a value, that case you can encapsulate both the operations into one. Something like you create a new function set_my_var(value)
function set_my_var(varvalue)
{
$this->my_var = varvalue;
$this->my_function();
}
Please look at the following code snipped
class A
{
function __get($name)
{
if ($name == 'service') {
return new Proxy($this);
}
}
function render()
{
echo 'Rendering A class : ' . $this->service->get('title');
}
protected function resourceFile()
{
return 'A.res';
}
}
class B extends A
{
protected function resourceFile()
{
return 'B.res';
}
function render()
{
parent::render();
echo 'Rendering B class : ' . $this->service->get('title');
}
}
class Proxy
{
private $mSite = null;
public function __construct($site)
{
$this->mSite = $site;
}
public function get($key)
{
// problem here
}
}
// in the main script
$obj = new B();
$obj->render();
Question is: in method 'get' of class 'Proxy', how I extract the corresponding resource file name (resourceFile returns the name) by using only $mSite (object pointer)?
What about:
public function get($key)
{
$file = $this->mSite->resourceFile();
}
But this requires A::resourceFile() to be public otherwise you cannot access the method from outside the object scope - that's what access modifiers have been designed for.
EDIT:
OK - now I think I do understand, what you want to achieve. The following example should demonstrate the desired behavior:
class A
{
private function _method()
{
return 'A';
}
public function render()
{
echo $this->_method();
}
}
class B extends A
{
private function _method()
{
return 'B';
}
public function render()
{
parent::render();
echo $this->_method();
}
}
$b = new B();
$b->render(); // outputs AB
But if you ask me - I think you should think about your design as the solution seems somewhat hacky and hard to understand for someone looking at the code.