简体   繁体   中英

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. First way with the 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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