Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

94
Views
PHP Class Extends a string variable

Is it possible to declare a class and have it extend a variable?

class Child extends $parentClass {}
about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Yes, it is with eval. But it is not recommended.

<?php
function dynamic_class_name() {
    if(time() % 60)
        return "Class_A";
    if(time() % 60 == 0)
        return "Class_B";
}
eval(
    "class MyRealClass extends " . dynamic_class_name() . " {" . 
    # some code string here, possibly read from a file
    . "}"
);
?>

Is Eval an evil?! Read this.

about 4 years ago · Santiago Trujillo Report

0

no you cant.

this is because in a normal definition:

class A extends SomeOtherClass {
}

SomeOtherClass is a namespace reference, not an instance of the class. And you cant use a variable to provide that namespace because variables in PHP are defined at runtime, whereas classes are defined in the compile phase.

But... if youre using PHP7, you can do this:

$newClass = new class extends SomeOtherClass {};

which is not exactly what you want, but goes some way.

about 4 years ago · Santiago Trujillo Report

0

A Class can not extend from a variable , You need to wrap the variable inside a class to extend . Hope this helps

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!