简体   繁体   English

如何在php类中调用函数?

[英]How can I call a function in a php class?

This is a sample code: 这是一个示例代码:

sample code 样例代码

I want to call it in another page: 我想在另一个页面中调用它:

include 'root of class file';
$r = new ImagineResizer();

I got this error: 我收到此错误:

Fatal error: Class 'ImagineResizer' not found in C:\WampDeveloper\Websites\example.com\webroot\images.php on line 13

Also call the function: 还调用函数:

$r->resize('c:/test1.jpg', 'c:/test2.jpg');

As seen in your sample code the class is located in another namespace : 如您的示例代码所示,该类位于另一个名称空间中:

<?php 

namespace Acme\MyBundle\Service;
use Symfony\Component\HttpFoundation\File\File;
use Imagine\Image\ImagineInterface;
use Imagine\Image\BoxInterface;
use Imagine\Image\Point;
use Imagine\Image\Box;

class ImagineResizer {
    //-- rest of code     
}

To use a class in another namespace you need to point out where the file is : First include the class (manual or with autoloading) 要在另一个命名空间中使用类,您需要指出文件的位置:首先包括该类(手动或自动加载)

Then u can create an instance in 2 ways. 然后,您可以通过2种方式创建实例。 First way with the use -keyword 第一种use -keyword

use Acme\MyBundle\Service\ImageResizer;
$object = new ImageResizer();

Or point to the class absolute : 或指向绝对类:

$object = new \Acme\MyBundle\Service\ImageResizer();

Hopefully, this will help you out some: 希望这会帮助您:

  1. Make sure you include the actual file - not just the folder where it lies. 确保包括实际文件,而不仅仅是文件所在的文件夹。
  2. Make sure that the file you're calling the class from uses the same namespace as your class file. 确保从中调用类的文件使用与类文件相同的名称空间。 If it doesn't, you have to call the class using the full namespace. 如果不是,则必须使用完整的名称空间调用该类。
  3. Profit. 利润。

The namespaces really had my patience go for a spin when I started using them, but once you're used to it it's not too hard. 当我开始使用名称空间时,确实让我耐心了一下,但是一旦习惯了,就不太难了。 I would recommend using an autoloader though. 我建议尽管使用自动装带器。 It's a bit of a hassle to set up, but once it's done it helps out a bunch. 设置起来有点麻烦,但是一旦完成,它就会帮上大忙。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM