PHP - Funciones Variables - Manual
PHP - Funciones Variables - Manual
Documentation
Get Involved
Help
Search docs
PHP 8.3.14 Released!
Getting Started
Introduction
A simple tutorial
Language Reference
Basic syntax
Types
Variables
Constants
Expressions
Operators
Control Structures
Functions
Classes and Objects
Namespaces
Enumerations
Errors
Exceptions
Fibers
Generators
Attributes
References Explained
Predefined Variables
Predefined Exceptions
Predefined Interfaces and Classes
Predefined Attributes
Context options and parameters
Supported Protocols and Wrappers
Security
Introduction
General considerations
Installed as CGI binary
Installed as an Apache module
Session Security
Filesystem Security
Database Security
Error Reporting
User Submitted Data
Hiding PHP
Keeping Current
Features
HTTP authentication with PHP
Cookies
Sessions
Handling file uploads
Using remote files
Connection handling
Persistent Database Connections
Command line usage
Garbage Collection
DTrace Dynamic Tracing
Function Reference
Affecting PHP's Behaviour
Audio Formats Manipulation
Authentication Services
Command Line Specific Extensions
Compression and Archive Extensions
Cryptography Extensions
Database Extensions
Date and Time Related Extensions
File System Related Extensions
Human Language and Character Encoding Support
Image Processing and Generation
Mail Related Extensions
Mathematical Extensions
Non-Text MIME Output
Process Control Extensions
Other Basic Extensions
Other Services
Search Engine Extensions
Server Specific Extensions
Session Extensions
Text Processing
Variable and Type Related Extensions
Web Services
Windows Only Extensions
XML Manipulation
GUI Extensions
Keyboard Shortcuts
?
This help
j
Next menu item
k
Previous menu item
gp
Previous man page
gn
Next man page
G
Scroll to bottom
gg
Scroll to top
gh
Goto homepage
gs
Goto search
(current page)
/
Focus search box
Manual de PHP
Referencia del lenguaje
Funciones
Funciones variables ¶
PHP admite el concepto de funciones variables. Esto significa que si un nombre de variable tiene paréntesis
anexos a él, PHP buscará una función con el mismo nombre que lo evaluado por la variable, e intentará
ejecutarla. Entre otras cosas, esto se puede usar para implementar llamadas de retorno, tablas de funciones, y así
sucesivamente.
Las funciones variables no funcionarán con constructores de lenguaje como echo, print, unset(), isset(), empty(),
include, require y similares. Utilice funciones de envoltura para hacer uso de cualquiera de estos constructores
como funciones variables.
<?php
function foo() {
echo "En foo()<br />\n";
}
$func = 'bar';
$func('prueba'); // Esto llama a bar()
$func = 'hacerecho';
$func('prueba'); // Esto llama a hacerecho()
?>
Los métodos de objetos también puede ser llamados con la sintaxis de funciones variables.
<?php
class Foo
{
function Variable()
{
$nombre = 'Bar';
$this->$nombre(); // Esto llama al método Bar()
}
function Bar()
{
echo "Esto es Bar";
}
}
?>
Cuando se llaman a métodos estáticos, la llamada a la función es más fuerte que el operador de propiedad
estática:
<?php
class Foo
{
static $variable = 'propiedad estática';
static function Variable()
{
echo 'Método Variable llamado';
}
}
echo Foo::$variable; // Esto imprime 'propiedad estática'. No necesita una $variable en este ámbito.
$variable = "Variable";
Foo::$variable(); // Esto llama a $foo->Variable() leyendo $variable en este ámbito.
?>
A partir de PHP 5.4.0, se puede llamar a cualquier callable almacenado en una variable.
<?php
class Foo
{
static function bar()
{
echo "bar\n";
}
function baz()
{
echo "baz\n";
}
}
Historial de cambios
Versión Descripción
7.0.0 'NombreDeClase::NombreDeMétodo' se permite como función variable.
5.4.0 Los arrays, que son llamables válidos, están permitidos como funciones variables.
Learn How To Improve This Page • Submit a Pull Request • Report a Bug
+add a note
$call = DEBUGME;
$call('abc'); // does the job
But you can use a constant as an argument to a function. Here's a simple workaround when you need to
call a variable constant function:
This makes sense to me to hide API's and/or long (complicated) static calls.
Enjoy!
up
down
2
rnealxp at yahoo dot com ¶
4 years ago
<?php
/*
You might have found yourself at this php variable functions page because, like me, you wanted to
pass functions
around like objects to client objects as you can in JavaScript. The issue I ran into was although
I could call a function using a variable like this " $v(); "...I could not do it like this " $obj-
>p() " where
'p' is a property containing the name of the method to call. Did not want to save my property off to
a variable prior
to making my call: " $v = $obj->p; $v(); "; even if one finds a way, the below applies...
I credit this expanded work to this person: tatarynowicz at gmail dot com;
without them I would not have gotten here.
*/
interface iface_dynamic_members{
//Use of this interface enables type-hinting for objects that implement it.
public function __call($name, $args);
public function __set($name, $value);
public function quietly_fail():bool;
}
trait trait_has_dynamic_members{
//Implementing these magic methods in the form of a trait, frees the client object up
//so it can still inherit from a parent-class.
public function __call($name, $args) {
if (is_callable($this->$name)) {
return call_user_func($this->$name, $args);
}
else {
//Your dynamic-membered object can declare itself as willing to ignore non-existent method calls or
not.
if($this->quietly_fail()===true){
echo 'Method does not exist, but I do not mind.';
}else{
echo 'Method does not exist, I consider this a bug.';
}
}
}
public function __set($name, $value) {
$this->$name = is_callable($value) ? $value->bindTo($this, $this): $value; //Assignment using ternary
operator.
}
}
abstract class MBR_ATTR{
//A class full of attributes that objects can take on; abstract since not to be instantiated (If I
could make it "final" as well, I would).
public static function is_a_walker(iface_dynamic_members $obj, ?string $walker_type='normal pace'){
$obj->walker_type = $walker_type;
$obj->walker_walk = function() {
return "I am walking {$this->walker_type}.";
};
}
public static function is_a_runner(iface_dynamic_members $obj, string $runner_type){
$obj->runner_type = $runner_type;
$obj->runner_run = function() {
return "I am running {$this->runner_type}.";
};
self::is_a_walker($obj); //If can run, also can walk.
}
}
class cls_partly_dynamic implements iface_dynamic_members{
use trait_has_dynamic_members;
public function quietly_fail():bool{
return true;
}
}
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE); //Enable all error-reporting except notices.
//----
//config runner object...
$obj_runner = new cls_partly_dynamic();
MBR_ATTR::is_a_runner($obj_runner, 'fast');
$obj_runner->runner_type = 'a bit slow';
//----
//config walker object...
$obj_walker = new cls_partly_dynamic();
MBR_ATTR::is_a_walker($obj_walker, 'slow');
$obj_walker->walker_type = 'super fast';
//----
//Do stuff...
echo 'walker in action...' . '<br>';
echo $obj_walker->walker_walk() . '<br>';
echo '<br>';
echo 'runner in action...' . '<br>';
echo $obj_runner->walker_walk() . '<br>';
echo $obj_runner->runner_run() . '<br>';
echo $obj_runner->xxx() . '<br>'; //Try calling a non-existent method.
//I would agree that the above approach/technique is not always ideal, particulary due to the loss of
code-completion in your
//IDE of choice; I would tend to use this approach for dynamic-programming in response to the user
dictating processing steps via a UI.
?>
up
down
3
Anonymous ¶
13 years ago
$ wget http://www.php.net/get/php_manual_en.tar.gz/from/a/mirror
$ grep -l "\$\.\.\." php-chunked-xhtml/function.*.html
Funciones
Funciones definidas por el usuario
Argumentos de funciones
Devolver valores
Funciones variables
Funciones internas (incluidas)
Funciones anónimas
Funciones de flecha
First class callable syntax
Search docs