---
title: "problem med __Autoload()"
type: "forum-thread"
url: "https://www.webforum.nu/amne/php/144336-problem-med-autoload"
topic: "PHP"
topic_url: "https://www.webforum.nu/amne/php"
author: "jme"
published: "2006-03-22T10:04:14.000Z"
updated: "2006-03-23T19:28:11.000Z"
replies: 5
views: 376
page: 1
pages: 1
language: "sv-SE"
site: "webForum — webforum.nu"
rights: "Upphovsrätten till varje inlägg tillhör dess författare."
attribution: "Citera som: webForum, https://www.webforum.nu/amne/php/144336-problem-med-autoload"
---

# problem med __Autoload()

## #1 — jme, 2006-03-22T10:04Z

Hej.

Hur fungerar \__autoload() egentligen?

Jag har klassen Test

```php
class Test
 	{
 		function __autoload($class)
		{
			require_once( 'classes' . $class . '.php');
		}
			 
	 	// prevent people from creating new instances of this class
	 	function __construct()
	 	{
	 		echo "Hello World";
	 	} 	
 	}
```

Försöker jag nu i en annan php-fil med:

new Test();

så får jag: Fatal error: Class 'Test' not found ...

Permalänk: https://www.webforum.nu/p/144336

## #2 — The_Hulk, 2006-03-22T10:10Z

inkluderar du din fil med classen Test från den filen du anropar Test()?
är detta rätt:

```php
$new Test();
```

Permalänk: https://www.webforum.nu/p/1786150

## #3 — jme, 2006-03-22T10:12Z

Dollar-tecknet ska bort.

Permalänk: https://www.webforum.nu/p/1786151

## #4 — jme, 2006-03-22T10:15Z

Grejen med autoload är väl att man inte ska behöva includa filerna?

Låt säga att jag har filen bil.php och i den har jag new Test(); 

men inget require_once("Test.php");

Permalänk: https://www.webforum.nu/p/1786156

## #5 — Sky, 2006-03-22T15:29Z

Du måste ha autoload i bil.php och inte i Test klassen.

Permalänk: https://www.webforum.nu/p/1786341

## #6 — prey, 2006-03-23T19:28Z

såvitt jag förstår så är \__autoload enbart en funktion direkt i php, den ska inte alls deklareras i någon klass eller så. Deklarera den högst upp i php-filen som körs först så borde det fungera bra sen.

```php
<?php
function __autoload($class)
{
   include($class . '.php');

   // Check to see if the include declared the class
   if (!class_exists($class, false)) {
       trigger_error("Unable to load class: $class", E_USER_WARNING);
   }
}
  
if (class_exists('MyClass')) {
   $myclass = new MyClass();
}

?>
```

Tillägg: funktionen class_exists kör automatiskt funktionen autoload om klassen inte är definierad (man kan gå runt detta och låta bli att autoloada med class_exists(namn, false).

> ```php
> // prevent people from creating new instances of this class
>          function __construct()
>          {
>              echo "Hello World";
>          }
> ```

 

För att förhindra instanser måste du kasta ett exception, som det ser ut nu kan man skapa hur många instanser som helst. Skriv istället 

```php
throw new Exception("Försök inte");
```

Permalänk: https://www.webforum.nu/p/1786857

---

Tråden på webben: https://www.webforum.nu/amne/php/144336-problem-med-autoload
