Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP: Cannot redeclare class error after return
    primarykey
    data
    text
    <p>I'm trying to protect classes being redeclared by returning based on if class_exists. This is common when creating plugins in Wordpress as there may be multiple plugins using the same classes. Using the following trivial example:</p> <p>You can view this on Youtube at <a href="http://www.youtube.com/watch?v=llVTvh6ffmw" rel="nofollow">http://www.youtube.com/watch?v=llVTvh6ffmw</a></p> <p>The following link demonstrates the problem and the root cause <a href="http://www.youtube.com/watch?v=VcNLoDvRLDc" rel="nofollow">http://www.youtube.com/watch?v=VcNLoDvRLDc</a></p> <p><strong>index.php</strong></p> <pre><code>&lt;?php include_once('debug1.php'); include_once('debug2.php'); $test = new SomeClass(); echo $test-&gt;someVar; </code></pre> <p><strong>debug1.php</strong> &amp; <strong>debug2.php</strong> are duplicate files...</p> <pre><code>&lt;?php if(class_exists('SomeClass')) return; class SomeClass { var $someVar = "test"; } </code></pre> <p>Despite having a return statement we still get a fatal error "cannot redeclare class".</p> <p>On a side note: Oddly 80% of the time this code has worked by simply adding/removing whitespace in debug2 - by work I mean it runs once then it breaks.</p> <p>I am running PHP version 5.4.4.</p> <p>So my question is. Is this expected behaviour? If yes, what am I missing. If no, is worrying as I've seen this in a few Wordpress plugins.</p> <p>Please note: I can get it to work every time with else wrapping, but this is more code...:</p> <pre><code>&lt;?php if(class_exists('SomeClass')) return; else { class SomeClass { var $someVar = "test"; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload