PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 22, 2022

[FIXED] What is the correct way to reference a sub-class of a PHP package when using Composer?

 January 22, 2022     cakephp, composer-php, php     No comments   

Issue

I have an application running in CakePHP 3 and have installed my packages via Composer.

Most recently I added phpspec/php-diff (https://packagist.org/packages/phpspec/php-diff) and ran composer update. It has put the files, as expected, in vendor/phpspec/php-diff/

I can instantiate the class in one of my CakePHP Controllers like this:

// src/Controller/UrlsController.php
// ...

use Diff;

public function test()
{
    $diff = new Diff(foo, bar);
    // This works
}

However, the documentation for this package gives this as an example on https://github.com/chrisboulton/php-diff/blob/master/example/example.php#L43 which comes after instantiating Diff (as done in test() above).

require_once dirname(__FILE__).'/../lib/Diff/Renderer/Html/Inline.php';
$renderer = new Diff_Renderer_Html_Inline;
echo $diff->render($renderer);

Obviously the require_once statement doesn't work because that's not where Inline.php lives in Composers hierarchy.

So how do you instantiate new Diff_Renderer_Html_Inline? If I just use it like this it errors saying

Class 'App\Controller\Diff_Renderer_Html_Inline' not found

Another workaround I thought may be to change the path in require_once so it points to it's location in vendor/. But surely there is a better solution?


Solution

If you're trying to refer to a class from within another namespace you need to refer to it using its fully qualified name e.g.

new \Diff_Renderer_Html_Inline;

Or add a use Diff_Renderer_Html_Inline after the namespace declaration to be able to do : new Diff_Renderer_Html_Inline



Answered By - apokryfos
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing