Как вызвать функцию от строки, сохраненной в переменной?

Я знаю, что это старо, но это может помочь кому-то еще, потому что это первое, что всплыло, когда я гуглил эту проблему. Я «позаимствовал» код для try и реализовал свой собственный метод try_method , который действует так же, как try , за исключением того, что он сначала проверяет, существует ли метод ранее вызов отправить . Я реализовал это в Object и поместил в инициализатор, и теперь я могу вызывать его для любого объекта.

class Object
  # Invokes the method identified by _method_, passing it any
  # arguments specified, just like the regular Ruby <tt>Object#send</tt> does.
  #
  # *Unlike* that method however, a +NoMethodError+ exception will *not* be raised
  # if the method does not exist.
  #
  # This differs from the regular Ruby <tt>Object#try</tt> method which only
  # suppresses the +NoMethodError+ exception if the object is Nil
  #
  # If try_method is called without a method to call, it will yield any given block with the object.
  #
  # Please also note that +try_method+ is defined on +Object+, therefore it won't work with
  # subclasses of +BasicObject+. For example, using try_method with +SimpleDelegator+ will
  # delegate +try_method+ to target instead of calling it on delegator itself.
  #
  # ==== Examples
  #
  # Without +try_method+
  #   @person && @person.respond_to?(:name) && @person.name
  # or
  #   (@person && @person.respond_to?(:name)) ? @person.name : nil
  #
  # With +try_method+
  #   @person.try_method(:name)
  #
  # +try_method+ also accepts arguments and/or a block, for the method it is trying
  #   Person.try_method(:find, 1)
  #   @people.try_method(:collect) {|p| p.name}
  #
  # Without a method argument try_method will yield to the block unless the receiver is nil.
  #   @person.try_method { |p| "#{p.first_name} #{p.last_name}" }
  #--
  # +try_method+ behaves like +Object#send+, unless called on +NilClass+ or a class that does not implement _method_.
  def try_method(method=nil, *args, &block)
    if method == nil && block_given?
      yield self
    elsif respond_to?(method)
      __send__(method, *args, &block)
    else
      nil
    end
  end
end

class NilClass
  # Calling +try_method+ on +nil+ always returns +nil+.
  # It becomes specially helpful when navigating through associations that may return +nil+.
  #
  # === Examples
  #
  #   nil.try_method(:name) # => nil
  #
  # Without +try_method+
  #   @person && @person.respond_to(:children) && !@person.children.blank? && @person.children.respond_to(:first) && @person.children.first.respond_to(:name) && @person.children.first.name
  #
  # With +try_method+
  #   @person.try_method(:children).try_method(:first).try_method(:name)
  def try_method(*args)
    nil
  end
end
271
задан Script47 8 September 2019 в 22:55
поделиться

5 ответов

444
ответ дан 23 November 2019 в 02:16
поделиться

Я не знаю, почему вы должны это использовать, это звучит не очень хорошо для меня, но если есть только небольшое количество функций, вы можете использовать конструкцию if / elseif. Я не знаю, возможно ли прямое решение.

что-то вроде $ foo = "бар"; $ test = "foo"; echo $$ test;

должен вернуть bar, вы можете попробовать, но я не думаю, что это сработает для функций

-9
ответ дан 23 November 2019 в 02:16
поделиться

Да, возможно:

function foo($msg) {
    echo $msg."<br />";
}
$var1 = "foo";
$var1("testing 1,2,3");

Источник: http://www.onlamp.com/pub/a/php/2001/05/17/php_foundations.html? page = 2

17
ответ дан 23 November 2019 в 02:16
поделиться

Для полноты картины вы также можете использовать eval () :

$functionName = "foo()";
eval($functionName);

Однако call_user_func () является правильным способом.

10
ответ дан 23 November 2019 в 02:16
поделиться

Используйте функцию call_user_func.

2
ответ дан 23 November 2019 в 02:16
поделиться
Другие вопросы по тегам:

Похожие вопросы: