Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use __dir__?

Tags:

php

dir

I want to use __dir__.

However, I can't find any good tutorial on how to set it up. I have my htdocs in Dropbox.

Does it work something like this?

 define(__DIR___, 'd:documents/dropbox/yolo/swag/htdocs/myproject/test/newtest/  testphp/test_new/testincludes/1/new_folder/') 

That is the directory where my project is located and it has sub folders. I want to include a file into another file that is in the parent folder.

Should I then just type:

 include'__DIR__/warlock.php';  

Or do I have to type something like this?

 include '___DIR__/wow/newb/guidesfornabz/classes/casters/warlock.php';  
like image 758
JosefPP Avatar asked Sep 12 '15 09:09

JosefPP


People also ask

What does __ DIR __ do in Python?

Python dir() function returns the list of names in the current local scope. If the object on which method is called has a method named __dir__(), this method will be called and must return the list of attributes.

What is __ DIR __ In laravel?

__DIR__ is the current directory you are in, if you wanted to go back one step, you could use dirname. This is used such as; dirname(__DIR__);

What is dirname (__ DIR __)?

__DIR__ : The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__) . This directory name does not have a trailing slash unless it is the root directory.

What is __ FILE __ in PHP?

__FILE__ is simply the name of the current file. realpath(dirname(__FILE__)) gets the name of the directory that the file is in -- in essence, the directory that the app is installed in.


1 Answers

You can use __DIR__ to get your current script's directory. It has been in PHP only since version 5.3, and it's the same as using dirname(__FILE__). In most cases it is used to include another file from an included file.

Consider having two files in a directory called inc, which is a subfolder of our project's directory, where the index.php file lies.

project ├── inc │   ├── file1.php │   └── file2.php └── index.php 

If we do include "inc/file1.php"; from index.php it will work. However, from file1.php to include file2.php we must do an include relative to index.php and not from file1.php (so, include "inc/file2.php";). __DIR__ fixes this, so from file1.php we can do this:

<?php include __DIR__ . "/file2.php"; 

To answer your question: to include the file warlock.php that is in your included file's upper directory, this is the best solution:

<?php include __DIR__ . "/../warlock.php"; 
like image 50
morganbaz Avatar answered Oct 05 '22 04:10

morganbaz