0

When using an external stylesheet, is it possible to use a PHP object within CSS - without creating another object?

I have found workarounds with internal and inline CSS (e.g. How to include PHP code in CSS?) Below is some minimal code to show the problem and the workarounds I have found thus far.

in MyClass.php:

class MyClass{
    public $color = "blue";
}

in PHP/HTML file:

<?php
include_once('MyClass.php');
$myClass = new MyClass();
?>

... (in head - internal CSS workaround):

<style type="text/css">
    h1{color: <?php echo $myClass->color;?>;} 
</style>

... (in head - external CSS workaround):

  <link rel="stylesheet"  href="external.css") />

... (in body):

<h1> 1. Internal </h1>
<h2 style="color:<?php echo $myClass->color;?>"> 2. Inline </h2>
<h3> 3. External </h3>

In external.css [here is the "problem" - I need to create a new object]:

<?php
    header('Content-type: text/css');
    include('myClass.php');
    $myClass = new MyClass(); //<--ANOTHER OBJECT
?>
h3 {
    color: <?=$myClass->color?>;
}
4
  • What's the problem? So you have to instantiate the object; so what? And to be clear, you do have to do that. You can't use an object from one request to the server in a different request. That's impossible. You can save and reload it, in theory, but you can't just reuse it. Commented Dec 22, 2016 at 21:26
  • What problem are you having? Have you configured your webserver to run .css files through PHP? Commented Dec 22, 2016 at 21:26
  • If you need to reuse an object from the original PHP file in the CSS file, you can use a session variable. Commented Dec 22, 2016 at 21:26
  • Thank you @Barmar -> I didn't think about a session variable. Indeed the webserver is configured (all the displayed code worked). Commented Dec 22, 2016 at 21:40

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.