如何在PHP中实现方法指针

时间:2013-11-15 12:38:54

标签: php class pointers methods

有没有办法在PHP中实现方法指针?

我一直收到以下错误:

  

致命错误:在第175行的/Users/sky/Documents/images.php中调用未定义的函数create_jpeg()

这是第175行:

if ($this->ImageType_f[$pImageType]($pPath) != 0)
class   CImage extends CImageProperties
{
  private $Image;
  private $ImagePath;
  private $ImageType;
  private function create_jpeg($pFilename)
  {
    if (($this->Image = imagecreatefromjepeg($pFilename)) == false)
      {
        echo "TEST CREATION JPEG\n";
        echo "Error: ".$pFilename.". Creation from (JPEG) failed\n";
        return (-1);
      }
    return (0);
  }
  private function create_gif($pFilename)
  {
    if (($this->Image = imagecreatefromgif($pFilename)) == false)
      {
        echo "Error: ".$pFilename.". Creation from (GIF) failed\n";
        return (-1);
      }
    return (0);
  }
  private function create_png($pFilename)
  {
    if (($this->Image = imagecreatefrompng($pFilename)) == false)
      {
        echo "Error: ".$pFilename.". Creation from (PNG) failed\n";
        return (-1);
      }
    return (0);
  }
  function __construct($pPath = NULL)
  {
    echo "Went through here\n";
    $this->Image = NULL;
    $this->ImagePath = $pPath;
    $this->ImageType_f['JPEG'] = 'create_jpeg';
    $this->ImageType_f['GIF'] = 'create_gif';
    $this->ImageType_f['PNG'] = 'create_png';
  }

  function __destruct()
  {
    if ($this->Image != NULL)
      {
        if (imagedestroy($this->Image) != true)
          echo "Failed to destroy image...";
      }
  }

  public function InitImage($pPath = NULL, $pImageType = NULL)
  {
    echo "pPath: ".$pPath."\n";
    echo "pImgType: ".$pImageType."\n";
    if (isset($pImageType) != false)
      {
        if ($this->ImageType_f[$pImageType]($pPath) != 0)
          return (-1);
        return (0);
      }
    echo "Could not create image\n";
    return (0);
  }
}

3 个答案:

答案 0 :(得分:1)

你的问题是行:

if ($this->ImageType_f[$pImageType]($pPath) != 0)

-since $this->ImageType_f[$pImageType]将产生一些字符串值,您的调用将等于调用全局函数,该函数不存在。你应该这样做:

if ($this->{$this->ImageType_f[$pImageType]}($pPath) != 0)

- 但这看起来很棘手,所以可能另一个好主意是使用call_user_func_array()

if (call_user_func_array([$this, $this->ImageType_f[$pImageType]], [$pPath]) != 0)

答案 1 :(得分:0)

只需使用$this->$method_name()调用所需的方法,其中$ method_name是包含所需方法的变量。

也可以使用call_user_funccall_user_func_array

这里描述了什么是可调用的:http://php.net/manual/ru/language.types.callable.php

因此,假设$this->ImageType_f['jpeg']'必须是可调用的:array($this, 'create_jpeg')

Alltogether:call_user_func($this->ImageType_f[$pImageType], $pPath)是实现目标的方式。

$this->ImageType_f['jpeg'] = 'create_jpeg'

$this->{$this->ImageType_f['jpeg']]($pPath);

我在这里提到的函数的一些文档:

http://us2.php.net/call_user_func http://us2.php.net/call_user_func_array

答案 2 :(得分:0)

我认为您需要使用此功能call_user_func 在你的情况下,电话会看起来像

call_user_func(array((get_class($this), ImageType_f[$pImageType]), array($pPath));