0

I would like to do the following:

<?php

session_start();

require_once "../includes/common.php";

$quoteShared = new quoteShared();

?>

common.php has:

<?php
require_once "../objects/quote/shared.php";
... plus many others
?>

This gives me the error of:

Fatal error: Class 'quoteShared' not found

I want to define classes separately to where I include them so I use the specific ones I need on different pages. Can it be done?

James Wilson
  • 809
  • 3
  • 14
  • 25
  • Yes. It's a very common practice. It seems that "quoteShared" is not found. This is probably because it's not loading it from shared.php. Double check your path. – durbnpoisn Jul 28 '14 at 13:15
  • Hmm OK seems fine but double checking now. What about "include" "require" and "require_once" - which should I use in example code block I posted? – James Wilson Jul 28 '14 at 13:18
  • I use `require` for classes that I load only once. If you are unsure, use `require_once`. Read the "[difference between require and include](http://stackoverflow.com/questions/3633900/difference-between-include-and-require-in-php)". – machineaddict Jul 28 '14 at 13:23
  • It's better to just split all your classes in custom files and than do a autoload like given as answer below. – Michal Jul 28 '14 at 13:28
  • Always use `require_once`. Personally I like the naming strategy something like `require_once __DIR__.'/../include/foo/bar/baz.class.php';` – Brandin Jul 28 '14 at 13:32

1 Answers1

1

That's a bad design strategy, you should take a look here: http://php.net/manual/en/language.oop5.autoload.php

ildanno
  • 119
  • 1
  • 6
  • 1
    It's not a bad strategy as everyone can code however it suites them. But a loader system would be usefull, I agree. – machineaddict Jul 28 '14 at 13:25
  • Thanks but I'm not sure this is for me. A lot of my classes are named based on the folder structure they are in. We have multiple products, and each product has 3 types of class depending on which part of the system you are in. So I have a class called "myaccountFootball" which is in /class/myaccount/football.php - this is why I think auto loader would fail for me! Keeping a common.php will do... – James Wilson Jul 28 '14 at 13:44
  • Actually your class naming can help in writing a custom autoloader (or several if you register them via spl). Anyway, if you're using php 5.3+ you can specify absolute path by using `__DIR__`, which represent the directory where your file is http://php.net/manual/en/language.constants.predefined.php – ildanno Jul 30 '14 at 07:13