PHP Constants in Classes - php

I have the following code sample, which produces an error with the included constant when it is run. Could someone please show me where this is going wrong?
class Template {
private $headers = "<link rel=\"stylesheet\" type=\"text/css\"
href=\"" . ROOT . "system/stylesheets/universal.css\" />";
... More variables and methods
}
Here is the error I receive. I am sure that the ROOT constant is defined, just outside of this class:
Parse error: syntax error, unexpected '.', expecting ',' or ';' in <page.php> on line <line number>
Thank you for your time,
spryno724

You cannot specify non-static values as your members default values. And you're trying to perform dynamic (runtime) things - concatenation of the strings.
class Template
{
public static headers()
{
return '<link rel="stylesheet" type="text/css" href="' . ROOT . 'system/stylesheets/universal.css" />';
}
}
Usage:
$headers = Template::headers()
Also - I missed that you're using just instance variables, not constants. In this case you can also use initialization in constructor:
class Template
{
private $headers;
public static __construct()
{
$this->headers = '<link rel="stylesheet" type="text/css" href="' . ROOT . 'system/stylesheets/universal.css" />';
}
}

Related

Setting scripts/rel in head tag of html layout in blade template

I started a new laravel application, and currently working on the main html template layout, I faced a issue.
I made a helper class that could set "version", so I can refresh the cache when I have new release.
namespace App\Http\Helpers;
class HTML
{
private const VERSION = '20180515';
private static function setVersion(&$file): void
{
$file = $file . '?v=' . self::VERSION;
}
public static function style(string $file): string
{
self::setVersion($file);
return '<link rel="stylesheet" type="text/css" href="' . $file . '">';
}
public static function script(string $file): string
{
self::setVersion($file);
return '<script src="' . $file . '"></script>';
}
}
And in the layout I use this:
...
<head>
...
{{ \App\Http\Helpers\HTML::style('css/layout.css') }}
</head>
Is there a way to use the HTML helper class so I don't have to call the namespaces every time?
Include in config/app.php
...
'aliases' => [
....
'HTML' => \App\Http\Helpers\HTML::class,
],
HTML is a common word and you may have some issues. If you have, use a differente key.
Anyway, you can then use
{!! HTML::style('css/layout.css') !!}
Also, if you have any issue, run
php artisan config:clear

Insert a CSS file within a PHP class

I have a little problem, which I can't figure out by myself.
I created sort of a "webengine", which I build out of several classes.
The main-class, getting a "theme's" internals is called "Logic".
This logic-class includes all the files, needed for a website. I made it like that, so that every developer, creating such website could use function, that are given inside this class.
I now want to create a function, that allows these developers to include a CSS file. But this turns out to be quite difficult.
So far I tried this:
public function include_css($path_to_css) {
$path_to_css = $this->project_name . THEMES . "/" . ACTIVE_THEME . "/" . $path_to_css;
if(file_exists($path_to_css)) {
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href=" <?php echo $path_to_css; ?>" />
</head>
<?php
} else {
return false;
}
}
/* Idea number 2 */
public function include_css($path_to_css) {
$path_to_css = $this->project_name . THEMES . "/" . ACTIVE_THEME . "/" . $path_to_css;
if(file_exists($path_to_css)) {
echo "
<html>
<head>
<link rel='stylesheet' type='text/css' href='".$path_to_css."' />
</head>
";
} else {
return false;
}
}
Please note that unclarified attributes are declared in a complex matter, so it would be a very long post, if I would paste these here.
I am just getting this console error: http://127.0.0.1/vpm2/themes/numberOne/css/test.css 404 (Not Found), which means there is no such file. The interesting thing about that, is, that this is the exact path to the right file!
Is there anything I am missing?
I found the solution. Apparently the CSS Path seems to be wrong. It needs to look like that:
$path_to_css = THEMES . "/" . ACTIVE_THEME . "/" . $path_to_css;
So the result looks like that:
themes/numberOne/test.css
Before it looked like that:
/vpm2/themes/numberOne/test.css

How to concatenate base url with another variable in code igniter

I need to concatenate the base url with another variable which should be public in the class. How can I do this?
Here is my code :
class site extends CI_Controller
{
public $site_favicon = base_url().'img/favicon.ico';
// I tried even public $site_favicon = base_url();.'img/favicon.ico';
}
Where i will call the variable $t publicly any where from the site.
How can i do this ?
This is how I will call:
<link rel="shortcut icon" href="<?php echo $this->site_favicon; ?>">
I am getting:
Parse error: syntax error, unexpected '(', expecting ',' or ';' in /opt/lampp/htdocs/ci/application/controllers/site.php on line 23
What mistake am I doing in concatenation and how can i fix this?
Try with this
class site extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('url'));
$url=$this->config->base_url();
$this->site_favicon=$url.'img/favicon.ico';
}
}
Now you can access site_favicon in functions with echo $this->site_favicon;
<link rel="shortcut icon" href="<?php echo $this->site_favicon ?>">
Note : If you want variables set in the constructor accessible, then you have to set them as a class property ie., like $this->variablename and access them in the same way with $this->variablename in your functions.
You can't assign function inside class varable, base_url is helper function, that is initialized in system autoload
So you can use directly in views
Try this way
<link rel="shortcut icon" href="<?php echo base_url("img/favicon.ico"); ?>">
OR
<link rel="shortcut icon" href="<?php echo base_url()."img/favicon.ico"; ?>">
UPDATE: You should assign favicon value in view variable, the view variables are defined in controller -> action method
In controller
$favicon = base_url().'img/favicon.ico';
$this->load->view("viewName", array("favicon" => $favicon));
In view you can access variable
<link rel="shortcut icon" href="<?php $favicon; ?>">
NOTE: you can't access controller class variable value directly in view

php undefined variable error when calling class method

I have been writing procedural php for years and am very comfortable with it. Recently I decided to rework an existing site and switch to PDO and OOP. Everyone is telling me that this is a better way to go but the learning curve is killing me. When trying to call a class, I get the following.
Menu Builder
vbls: 5 1
Notice: Undefined variable: Menu in /home/lance/DallyPost/projectWebSite/trunk/1/core/modules/menuBuilder.php on line 9
Fatal error: Call to a member function menuFramework() on a non-object in /home/lance/DallyPost/projectWebSite/trunk/1/core/modules/menuBuilder.php on line 9
The procedure is that I have included menu.php at the top of index.php, prior to including the following script:
<?php
//menuBuilder.php
echo"<h2>$pageTitle</h2>";
$pub = $_URI_KEY['PUB'];
$dir = $_URI_KEY['DIRECTORY'];
echo"vbls: $pub $dir";
if($Menu->menuFramework("$pub", "$dir") === false) {
echo"The base menu framework failed to build correctly.";
}
else{
echo"<p>The base menu framework has been successfully constructed.</p>";
}
?>
As you can see, the above script calls a method in the Menu class:
<?php
//menu.php
class Menu{
private $db;
public function __construct($database) {
$this->db = $database;
}
public function menuFramework($pub, $directory){
$link = "/" . $directory . "/index.php/" . $pub . "/home/0/Home-Page/";
$inc = "core/menus/" . $pub . "category.php";
$file = "core/menus/" . $pub . "menuFramework.php";
$text = "<nav class=\"top-bar\" data-topbar>";
$text .= "<ul class=\"title-area\">";
$text .= "<li class=\"name\">";
$text .= "<h1>Home Page</h1>";
$text .= "</li>";
$text .= "</ul>";
$text .= "include($inc)";
$text .= "</nav>";
//write text to a file
if(file_put_contents($file, $text)){
return true;
}
else{
return false;
}
}
... rest of file not shown
Can you help me understand why I am getting this error. My understanding is that the variable was or should have been defined when I included menu.php, which was done before which was called a the top if index.php
Thanks
add this at the top of the script
$menu = new Menu($dbHandle);
That's not how classes work. You can't reference an entire class, Menu, with a variable, $Menu, to invoke instance methods.
You need to create an instance of your class on which to invoke methods:
$menu = new Menu(...);
You can create class-level "static" methods which are invoked on the class itself, but that syntax doesn't involve $Menu. You would use Menu::method_name() for that.
You are calling $Menu->
so your are a calling a variable called Menu, instead of the class Menu.
anyways, that function is not static, so you need to instantiate an object.
For that, add a this line:
$menu = new Menu($db);
where $db is your database object, if you really need it, or null if you dont (i cannot say with that code fragment)
and then call
$menu->menuFramework(...)

'Call to undefined function' - Trying to call function from an included file

So I have two files, 'header.php' and 'pluginfile.php'
The function that I want to call resides in 'pluginfile.php' and is:
public function getNonSubscriptionAmount() {
$total = 0;
foreach($this->_items as $item) {
if(!$item->isSubscription()) {
$total += $item->getProductPrice() * $item->getQuantity();
}
else {
// item is subscription
$basePrice = $item->getBaseProductPrice();
Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Item is a subscription with base price $basePrice");
$total += $basePrice;
}
}
return $total;
}
So in 'header.php' I have:
<?php
include_once($_SERVER['DOCUMENT_ROOT']."/wp-content/plugins/plugin-name/folder/PluginFile.php");
print getNonSubscriptionAmount();
?>
This gives the following error when any page is loaded:
Fatal error: Call to undefined function getnonsubscriptionamount() in
/home/username/domain.com/wp-content/themes/theme/header.php on
line 72
I've spent a couple of hours now trying to figure this out alone and am getting nowhere! Any help much appreciated!
#Wiseguy looks like he had the right idea put in the comments.
You are declaring a method and not a function. Is the function the entirety of your plugin.php file or is there more? If it is everything, remove the public modifier and just declare
function getNonSubscriptionAmount() {
// code here
}
But from the looks of the code it is part of a larger class. If thats the case then #Wiseguy comment is right on, you need to instantiate a new object of the class in plugin.php and then the desired method.
$obj = new PluginClass();
$obj->getNonSubscriptionAmount();
You said:
The function that I want to call resides in 'plugin.php' and is:
And in your file you are including:
So in 'header.php' I have:
include_once($_SERVER['DOCUMENT_ROOT']."/wp-content/plugins/plugin-name/folder/PluginFile.php");
print getNonSubscriptionAmount();
You are not including 'plugin.php' which is were the function lives.
Header.php should include 'plugin.php', not 'PluginFile.php'.

Categories