user1032531
user1032531

Reputation: 26281

Dealing with declaring class twice in PHP

I am using the 3rd party ostickets application. Line 17 of include/class.passwd.php includes the code require_once(INCLUDE_DIR.'PasswordHash.php'); which creates an object using class PasswordHash {...}.

My problem is I use the 3rd party class PashwordHash earlier in my script independently of ostickets, and my first use of the PasswordHash needs to come before when used with ostickets.

Since ostickets comes as a package, it includes its own copy of PasswordHash.php, thus required_once doesn't prevent the class from being declared twice. I would rather not modify the osticket package using something like if(!class_exists('PasswordHash')){require_once(INCLUDE_DIR.'PasswordHash.php');} as this will cause problems if I upgrade ostickets and forget to make the changes.

I would also rather not modify the first file which includes the PasswordHash class by changing the class name again to allow future upgrades without problems.

My options as I see them...

  1. Modify one of the 3rd party libraries even though I would rather not.
  2. Somehow declare the class when I first use it, and somehow "destroy it" and then go on with my business with ostickets. I don't think this is possible, but am not sure.
  3. Create a namespace when I first use PasswordHash. Is this a viable option, and if so, how?
  4. Maybe something else which I have not thought of?

Thanks

Upvotes: 3

Views: 1386

Answers (1)

user215361
user215361

Reputation:

This is indeed what namespaces are for:

<?php

  namespace NiceNamespaceName;

  class PasswordHash
  {
  }

?>

Then you can use it as such:

<?php
  $hash = new \NiceNamespaceName\PasswordHash();
?>

Upvotes: 4

Related Questions